一. 简介

matplotlib.pyplotis a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

In matplotlib.pyplotvarious states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that “axes” here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).

Note
the pyplot API is generally less-flexible than the object-oriented API. Most of the function calls you see here can also be called as methods from an Axes object.

二.文档

Pyplot入门教程及本文实例参考 Pyplot tutorial

三.食用方法

1.基础折线图绘制plot()

绘制(0,0),(1,1),(2,1),(3,3)四个点连成的折线

  1. import matplotlib.pyplot as plt
  2. x=[0,1,2,3]
  3. y=[0,1,1,3]
  4. plt.plot(x,y)
  5. plt.show()

image.png

2.修改折线图的颜色/线的形状

  1. plt.plot(x,y,'r') # 修改颜色,rgb=红绿蓝,默认为蓝
  2. plt.plot(x,y,'--') # 修改线的形状为虚线,默认为折线'-',另外'o'为点,'^'为三角
  3. plt.plot(x,y,'g--') # 一起修改为绿色虚线
  4. plt.axis([1,6,0,5]) # 修改坐标轴x刻度显示(xmin,xmax,ymin,ymax)

image.png

3.只输入一维数据的情形

plt.plot(x,y)接受点集(x,y),当只输入一维数据的时候当作y轴处理,x轴默认生成[0,1,2,…]
例如,绘制4个独立的点(0,1),(1,1),(2,1),(3,1)

  1. y=[1,1,1,1]
  2. plt.plot(y,'ro')
  3. plt.show()

image.png

4.list与Arrays

教程原文

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally.

考虑到性能问题,意味着所有的序列(包括list等)会在内部转换为numpy.array

  1. t1=[1,5,1,5] #list会被转换为t2的类型
  2. t2=np.array([5,1,5,1]) #numpy.array
  3. plt.plot(t1)
  4. plt.plot(t2)
  5. plt.show()

5.在一张图中显示多个图表

在4中,分别使用了两次plt.plot()载入t1和t2,也可以用一条语句

  1. plt.plot(t1,'b--',t2,'r--')

对于两组(x,y)坐标,如下

  1. x1=[1,2,3,4]
  2. y1=[1,2,3,4]
  3. x2=[2,4,6,8]
  4. y2=[4,8,12,16]
  5. plt.plot(x1,y1,'r-',x2,y2,'g--')
  6. plt.show()

image.png

6.绘制标准函数曲线:sin()与cos()

绘制f(x)=sin(x) 和g(x)=cos(x) 在x∈[0,20]中的图像

  1. x = np.arange(0, 20, 0.01)
  2. plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b--')
  3. plt.axis([0,20,-3,3])
  4. plt.show()

image.png

7.显示网格线

  1. x = np.arange(0, 20, 0.01)
  2. plt.plot(x, x**2)
  3. plt.grid(True) # 设置网格线
  4. plt.show()

image.png

8.增加标注

以7中的函数图像为例,注意:输入中文会出现方块乱码。

(1)增加x,y轴文字

  1. plt.xlabel("Money Earned")
  2. plt.ylabel("Consume Level")

(2)增加标题

  1. plt.title("Figure.1")

(3).图内文字

指定首字出现的x轴,y轴,文字本身

  1. plt.text(2.5,100,"TEXT1")

(4)箭头指示

指定文字,箭头指向的坐标,文字显示的坐标,箭头的属性

  1. plt.annotate('max value', xy=(20, 400), xytext=(12.5, 400),
  2. arrowprops=dict(facecolor='black', shrink=0.05),
  3. )

(5)综合结果图

image.png

9.设置文本属性

对text(),xlabel(),ylabel(),title(),annotate()等可使用参数设置文本属性
例如

  1. plt.xlabel("Money Earned",color="r",fontsize=20)

可选参数如下,这里只列出常用属性,更多属性请查阅
https://matplotlib.org/api/text_api.html#matplotlib.text.Text

Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c color
contains callable
figure Figure
fontfamily or family {FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’}
fontproperties or font_properties font_manager.FontProperties
fontsize or size {size in points, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
fontstretch or stretch {a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’}
fontstyle or style {‘normal’, ‘italic’, ‘oblique’}
fontvariant or variant {‘normal’, ‘small-caps’}
fontweight or weight {a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’}
gid str
horizontalalignment or ha {‘center’, ‘right’, ‘left’}
in_layout bool
label object
linespacing float (multiple of font size)
multialignment or ma {‘left’, ‘right’, ‘center’}
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool or None
rotation {angle in degrees, ‘vertical’, ‘horizontal’}
rotation_mode {None, ‘default’, ‘anchor’}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
url str
usetex bool or None
verticalalignment or va {‘center’, ‘top’, ‘bottom’, ‘baseline’, ‘center_baseline’}
visible bool
wrap bool
x float
y float
zorder float

10.设置曲线属性

plt.plot()返回matplotlib.lines.Line2D,可以通过变量获得并修改曲线Line2D的属性

  1. x=np.arange(0,10,0.01)
  2. line1,line2=plt.plot(x,np.sin(x),'-',x,np.cos(x),'--') #line1得到2D Lines
  3. plt.setp(line1,color='r',linewidth='11.0') #设置曲线的宽度
  4. plt.show()

image.png

11.解决中文乱码

利用9中修改字体为中文字体就能轻松解决乱码

(1)指定为文件目录中的字体

  1. from matplotlib.font_manager import FontProperties
  2. font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc")
  3. plt.xlabel("中文文本", fontproperties=font)

(2)指定为系统字体

  1. plt.xlabel("中文文本",fontname='SimHei',size=20)
  2. #或者
  3. plt.xlabel("中文文本",fontproperties='SimHei',fontsize=20)#size要放在后面,否则会被覆盖

(3)全局设置

  1. font = {'family' : 'SimHei',
  2. 'weight' : '50',
  3. 'size' : '30'}
  4. plt.rc('font', **font)
  5. plt.xlabel("中文文本")

12.修改坐标轴刻度

(1)指定刻度范围

  1. plt.axis([0,6,1,5]) #设定x轴刻度在(0,6) y轴刻度在(1,5)
  2. plt.axis('off') #关闭刻度

(2)子图的刻度修改

  1. axes[0,0].set_xticks([0,250,750,1000]) #设置x轴
  2. axes[0,0].set_xticklabels(['one','two','three'],rotation=30) #将数值改为标签,并旋转30度显示

(3)使用刻度函数
以教程例子为例
image.png
四种不同的刻度

  1. plt.yscale('linear')
  2. plt.yscale('log')
  3. plt.yscale('symlog')
  4. plt.yscale('logit')

上述四图的例子代码如下

  1. from matplotlib.ticker import NullFormatter # useful for `logit` scale
  2. # Fixing random state for reproducibility
  3. np.random.seed(19680801)
  4. # make up some data in the interval ]0, 1[
  5. y = np.random.normal(loc=0.5, scale=0.4, size=1000)
  6. y = y[(y > 0) & (y < 1)]
  7. y.sort()
  8. x = np.arange(len(y))
  9. # plot with various axes scales
  10. plt.figure(1)
  11. # linear
  12. plt.subplot(221)
  13. plt.plot(x, y)
  14. plt.yscale('linear')
  15. plt.title('linear')
  16. plt.grid(True)
  17. # log
  18. plt.subplot(222)
  19. plt.plot(x, y)
  20. plt.yscale('log')
  21. plt.title('log')
  22. plt.grid(True)
  23. # symmetric log
  24. plt.subplot(223)
  25. plt.plot(x, y - y.mean())
  26. plt.yscale('symlog', linthreshy=0.01)
  27. plt.title('symlog')
  28. plt.grid(True)
  29. # logit
  30. plt.subplot(224)
  31. plt.plot(x, y)
  32. plt.yscale('logit')
  33. plt.title('logit')
  34. plt.grid(True)
  35. # Format the minor tick labels of the y-axis into empty strings with
  36. # `NullFormatter`, to avoid cumbering the axis with too many labels.
  37. plt.gca().yaxis.set_minor_formatter(NullFormatter())
  38. # Adjust the subplot layout, because the logit one may take more space
  39. # than usual, due to y-tick labels like "1 - 10^{-3}"
  40. plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
  41. wspace=0.35)
  42. plt.show()

13.圆形/矩形/椭圆patches

  1. import matplotlib.pyplot as plt
  2. import matplotlib.patches as patches
  3. fig = plt.figure()
  4. ax1 = fig.add_subplot(111,aspect='equal') #1x1一张图中的第1张,equal为等宽显示
  5. rec=patches.Rectangle((0, 0), 8, 4) #顶点坐标(0,0) 宽w=8 高h=4
  6. cir=patches.Circle((8,8),2) #圆心坐标(8,8) 半径r=1
  7. ell=patches.Ellipse((2,8),6,3) #椭圆左顶点坐标(2,8) 长轴c1=6 短轴c2=3
  8. ax1.add_patch(rec) #插入patch图像
  9. ax1.add_patch(cir)
  10. ax1.add_patch(ell)
  11. plt.plot() #显示多个
  12. plt.show()

patches中还有许多种图形,例如各种箭头,箭,多边形等。
image.png

14.绘制直方图-标准正态分布hist()

plt.hist()用于绘制直方图

常用参数 描述
arr 需要计算的一维数组
bins

直方图的柱数,默认为10
normed
是否将得到的直方图向量归一化


facecolor
直方图颜色

edgecolor

直方图边框颜色
alpha
透明度
histtype 直方图类型 {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}
返回值 描述
n 直方图向量,是否归一化由参数
normed 设定bins返回各个bin的区间范围
patches 以list形式返回每个bin里面包含的数据

标准正态分布又称为μ分布,是以均数μ=0、标准差σ=1的正态分布,记为N(0,1)
代码如下

  1. mu, sigma = 0,1
  2. x = np.random.normal(mu,sigma,10000)
  3. n, bins, patches = plt.hist(x,bins=100,facecolor='g', alpha=0.75)
  4. plt.text(-3, 250, r'$\mu=0,\ \sigma=1$')
  5. plt.grid(True)
  6. plt.show()

image.png

15.绘制散点图scatter()

plt.scatter()用于绘制散点图

参数 描述
x
坐标x轴集合

y
坐标y轴集合

c
散点的颜色数目,默认为纯色

s
散点的大小数目
alpha 透明度

例:绘制正态分布随机1000个点的位置分布

  1. x = np.random.normal(0, 1, 1000) # 1000个点的x坐标
  2. y = np.random.normal(0, 1, 1000) # 1000个点的y坐标
  3. c = np.random.rand(1000) #1000个颜色
  4. s = np.random.rand(100)*100 #100种大小
  5. plt.scatter(x, y, c=c, s=s,alpha=0.5)
  6. plt.grid(True)
  7. plt.show()

image.png

16.显示多个图表

  1. names = ['Anime', 'Comic', 'Game']
  2. values = [30, 10, 20]
  3. plt.subplot(221) #构建2x2张图中的第1张子图
  4. plt.bar(names, values) #统计图
  5. plt.subplot(222)
  6. plt.scatter(names, values) #散点图
  7. plt.subplot(223)
  8. plt.plot(names, values) #折线图
  9. plt.suptitle('三种图示',fontname='SimHei')
  10. plt.show()

image.png
上述是每次构造一个子图,然后在子图中绘制.也可以先构造所有的子图,再通过下标指定在哪张子图中绘制

  1. fig,axes=plt.subplots(2,2) #构造2x2的子图
  2. axes[0,1].plot(names, values) #通过下标访问
  3. axes[1,0].scatter(names, values)
  4. axes[1,1].bar(names, values)
  5. plt.show()

image.png

17.调整子图间隔

  1. fig,axes=plt.subplots(2,2,sharex=True,sharey=True) #构造2x2的子图,子图共享x,y轴
  2. for i in range(2):
  3. for j in range(2):
  4. axes[i,j].hist(np.random.rand(500),bins=100,alpha=0.7,color='k')
  5. plt.subplots_adjust(hspace=0,wspace=0) #修改内部的宽,高间距为0
  6. plt.show()

(在python3.7中无法得到和书中一致的结果,即实现没有内部子图间隔的数据可视化)

image.png

18.绘制柱状图

垂直柱状图plt.bar(name,values)
水平柱状图plt.barh(name,values)

  1. x=np.random.randint(1,10,8)
  2. label=list('abcdefgh')
  3. plt.subplot(211)
  4. plt.bar(label,x)
  5. plt.subplot(212)
  6. plt.barh(label,x)
  7. plt.show()

image.png
两组数据比较的垂直柱状图
这里不再使用plt.bar(),而是使用pd.DataFrame.plot.bar()

  1. x=np.random.randint(1,10,8)
  2. y=np.random.randint(1,10,8)
  3. data=pd.DataFrame([x,y],index=['X','Y'],columns=list('abcdefgh'))
  4. >>> data
  5. data
  6. a b c d e f g h
  7. X 6 2 9 5 5 2 7 7
  8. Y 6 6 9 1 1 5 2 4
  9. data.plot.bar()
  10. plt.show()

image.png
得到以index为分类,columns为数据的柱状图
两组数据交叉比较的垂直柱状图,只需交换index和columns即可

  1. data.transpose().plot.bar() #data.transpose()转置
  2. plt.show()

image.png