Matplotlib 系列文章:
专栏:
【NumPy 专栏】【Pandas 专栏】【Matplotlib 专栏】
推荐学习资料与网站:
【NumPy 中文网】【Pandas 中文网】【Matplotlib 中文网】【NumPy、Matplotlib、Pandas 速查表】
1 2 3 4 5
| 这里是一段防爬虫文本,请读者忽略。 本文原创首发于 CSDN,作者 TRHX。 博客首页:https://itrhx.blog.csdn.net/ 本文链接:https://itrhx.blog.csdn.net/article/details/105839855 未经授权,禁止转载!恶意转载,后果自负!尊重原创,远离剽窃!
|
【1x00】方法描述
matplotlib.pyplot.plot()
函数可以用于绘制线性图。
本文用到的其他图像属性可参考前面的两篇文章:
《Python 数据分析三剑客之 Matplotlib(二):文本描述 / 中文支持 / 画布 / 网格等基本图像属性》
《Python 数据分析三剑客之 Matplotlib(三):图例 / LaTeX / 刻度 / 子图等基本图像属性》
基本语法:matplotlib.pyplot.plot(x, y[, fmt, \*\*kwargs])
参数 |
描述 |
x |
x 轴数据,数组类型或者标量,x 值是可选的,默认为 range(len(y)) ,通常为一维数组 |
y |
y 轴数据,数组类型或者标量,通常为一维数组 |
fmt |
str 类型,格式字符串,由标记、线条和颜色部分组成
fmt = '[marker][line][color]' ,例如 ro 表示红色圆圈,三个参数的取值见后表 |
**kwargs |
可选项,其他 Line2D 属性,常用属性见下表 |
部分常见 Line2D 属性如下表,完整属性参见官方文档。
属性 |
描述 |
alpha |
线条透明度,float 类型,取值范围:[0, 1] ,默认为 1.0,即不透明 |
antialiased / aa |
是否使用抗锯齿渲染,默认为 True |
color / c |
线条颜色,支持英文颜色名称及其简写、十六进制颜色码等,更多颜色示例参见官网 Color Demo |
linestyle / ls |
线条样式:'-' or 'solid' , '--' or 'dashed' , '-.' or 'dashdot' ':' or 'dotted' , 'none' or ' ' or '' |
linewidth / lw |
线条宽度,float 类型,默认 0.8 |
markeredgecolor / mec |
marker 标记的边缘颜色 |
markeredgewidth / mew |
marker 标记的边缘宽度 |
markerfacecolor / mfc |
marker 标记的颜色 |
markerfacecoloralt / mfcalt |
marker 标记的备用颜色 |
markersize / ms |
marker 标记的大小 |
fmt 中 marker
、line
、color
三个参数的取值:
marker:线条标记样式(线条上每个数据点的样式) |
字符 |
描述 |
'.' |
点标记(point marker) |
',' |
像素点标记(pixel marker) |
'o' |
圆圈标记(circle marker) |
'v' |
下三角标记(triangle_down marker) |
'^' |
上三角标记(triangle_up marker) |
'<' |
左三角标记(triangle_left marker) |
'>' |
右三角标记(triangle_right marker) |
'1' |
下三叉星标记(tri_down marker) |
'2' |
上三叉星标记(tri_up marker) |
'3' |
左三叉星标记(tri_left marker) |
'4' |
右三叉星标记(tri_right marker) |
's' |
正方形标记(square marker) |
'p' |
五角形标记(pentagon marker) |
'*' |
星号标记(star marker) |
'h' |
六边形标记(hexagon1 marker) |
'H' |
六边形标记(hexagon2 marker) |
'+' |
加号标记(plus marker) |
'x' |
X 号标记(x marker) |
'D' |
菱形标记(diamond marker) |
'd' |
细菱形标记(thin_diamond marker) |
`’ |
‘` |
垂直线标记(vline marker) |
'_' |
水平线标记(hline marker) |
字符 |
描述 |
'-' |
实线样式(solid line style) |
'--' |
虚线样式(dashed line style) |
'-.' |
点划线样式(dash-dot line style) |
':' |
点样式(dotted line style) |
color:线条颜色,支持英文颜色名称及其简写、十六进制颜色码等
|
字符 |
描述 |
'b' |
蓝色(blue) |
'g' |
绿色(green) |
'r' |
红色(red) |
'c' |
青色(cyan) |
'm' |
品红(magenta) |
'y' |
黄色(yellow) |
'k' |
黑色(black) |
'w' |
白色(white) |
fmt 举例:
1 2 3 4 5
| 'b' 'or' '-g' '--' '^k:'
|
【2x00】基本示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y = np.sin(3*x)/x plt.title('线性图示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y) plt.show()
|

【3x00】多条数据
绘制多条数据,设置不同数据,然后多次调用 plt.plot()
函数即可,不同数据的线条颜色会不同,系统随机,可单独指定不同颜色。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('多数据线性图示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y1) plt.plot(x, y2) plt.plot(x, y3)
plt.show()
|

【4x00】设置颜色 / 样式 / 图例
设置线条颜色样式等属性直接在 plot()
函数里面添加相应参数即可,设置图例则需要调用 legend()
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x1 = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x1)/x1 y2 = np.sin(2*x1)/x1
x3 = np.arange(-2*np.pi, 2*np.pi, 2) y3 = np.array([0, 2, 1.5, 1, 2.4, -0.2, 1.7])
plt.title('线性图自定义样式示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x1, y1, '--r', label='x1, y1') plt.plot(x1, y2, color='green', label='x1, y2') plt.plot(x3, y3, marker='o', mfc='r', linestyle=':', label='x3, y3') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')
plt.show()
|

1 2 3 4 5
| 这里是一段防爬虫文本,请读者忽略。 本文原创首发于 CSDN,作者 TRHX。 博客首页:https://itrhx.blog.csdn.net/ 本文链接:https://itrhx.blog.csdn.net/article/details/105839855 未经授权,禁止转载!恶意转载,后果自负!尊重原创,远离剽窃!
|
【5x00】设置刻度
调用 xticks()
和 yticks()
函数可以对坐标刻度进行自定义,该函数接收两个参数,第一个参数表示要显示的刻度位置,第二个参数表示在对应刻度线上要显示的标签信息,标签信息支持 LeTeX 数学公式,使用时要用美元符号 $
包围起来。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('线性图设置刻度示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')
plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))
plt.show()
|

【6x00】隐藏画布边框
Matplotlib 所绘制的图表中的每个绘图元素,例如线条 Line2D、文字 Text、刻度等在内存中都有一个对象与之对应。
matplotlib.pyplot.gca()
函数用于获取当前的绘图区 Axes
(Get Current Axes)
matplotlib.pyplot.gcf()
函数用于获取当前的画布 Figure
(Get Current Figure)
例如:matplotlib.pyplot.plot()
实际上会通过 matplotlib.pyplot.gca()
获得当前的 Axes
对象 ax
,然后再调用 ax.plot()
方法实现真正的绘图。我们可以通过这种方法来实现画布边框的隐藏和坐标轴的移动。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('线性图隐藏画布边框示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')
plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))
ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)
plt.show()
|

【7x00】移动坐标轴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('线性图移动坐标轴示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')
plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))
ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)
ax.spines['left'].set_position(('data', 0)) ax.spines['bottom'].set_position(('data', 0)) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left')
plt.show()
|

【8x00】指定位置显示文本
matplotlib.pyplot.annotate()
方法可以在指定坐标点添加文本或 LaTeX 描述,也可以在其他位置添加描述后,使用箭头指向某个坐标点。
基本语法:matplotlib.pyplot.annotate(text, xy, xytext, xycoords, textcoords, ha, va, arrowprops, \*\*kwargs)
参数 |
描述 |
text |
str 类型,注释的文本 |
xy |
被注释的坐标点,格式:(x, y) |
xytext |
注释文本的坐标点,格式:(x, y) ,默认与 xy 相同 |
xycoords |
被注释的坐标点的参考系,取值参见表一,默认为 ‘data’ |
textcoords |
注释文本的坐标点的参考系,取值参见表二,默认为 xycoords 的值 |
ha |
注释点在注释文本的左边、右边或中间(left 、right 、center ) |
va |
注释点在注释文本的上边、下边、中间或基线 (top 、bottom 、center 、baseline ) |
arrowprops |
dict 字典类型,箭头的样式 如果 arrowprops 不包含键 arrowstyle,则允许的键参见表三 如果 arrowprops 包含键 arrowstyle,则允许的键参见表四 |
取值 |
描述 |
‘figure points’ |
以画布左下角为参考,单位为点数 |
‘figure pixels’ |
以画布左下角为参考,单位为像素 |
‘figure fraction’ |
以画布左下角为参考,单位为百分比 |
‘axes points’ |
以绘图区左下角为参考,单位为点数 |
‘axes pixels’ |
以绘图区左下角为参考,单位为像素 |
‘axes fraction’ |
以绘图区左下角为参考,单位为百分比 |
‘data’ |
使用被注释对象的坐标系,即数据的 x, y 轴(默认) |
‘polar’ |
使用(θ,r)形式的极坐标系 |
取值 |
描述 |
‘figure points’ |
以画布左下角为参考,单位为点数 |
‘figure pixels’ |
以画布左下角为参考,单位为像素 |
‘figure fraction’ |
以画布左下角为参考,单位为百分比 |
‘axes points’ |
以绘图区左下角为参考,单位为点数 |
‘axes pixels’ |
以绘图区左下角为参考,单位为像素 |
‘axes fraction’ |
以绘图区左下角为参考,单位为百分比 |
‘data’ |
使用被注释对象的坐标系,即数据的 x, y 轴 |
‘polar’ |
使用(θ,r)形式的极坐标系 |
‘offset points’ |
相对于被注释点的坐标 xy 的偏移量,单位是点 |
‘offset pixels’ |
相对于被注释点的坐标 xy 的偏移量,单位是像素 |
表三:arrowprops 不包含键 arrowstyle 时的取值 |
表四:arrowprops 包含键 arrowstyle 时的取值 |
取值 |
描述 |
'-' |
None |
'->' |
head_length=0.4,head_width=0.2 |
'-[' |
widthB=1.0,lengthB=0.2,angleB=None |
']-' |
widthA=1.0, lengthA=0.2, angleA=None |
]-[ |
widthA=1.0, lengthA=0.2, angleA=None, widthB=1.0, lengthB=0.2, angleB=None |
`’ |
- |
‘` |
widthA=1.0,widthB=1.0 |
`’- |
>’` |
head_length=0.4,head_width=0.2 |
'<-' |
head_length=0.4,head_width=0.2 |
'<->' |
head_length=0.4,head_width=0.2 |
`’< |
-‘` |
head_length=0.4,head_width=0.2 |
`’< |
- |
>’` |
head_length=0.4,head_width=0.2 |
'fancy' |
head_length=0.4,head_width=0.4,tail_width=0.4 |
'simple' |
head_length=0.5,head_width=0.5,tail_width=0.2 |
'wedge' |
tail_width=0.3,shrink_factor=0.5 |
表五:matplotlib.patches.FancyArrowPatch 常用的键 |
键 |
描述 |
arrowstyle |
箭头样式,取值参见表四 |
connectionstyle |
连接方式,默认为 arc3 ,有以下五种取值:
angle :angleA=90, angleB=0, rad=0.0
angle3 :angleA=90, angleB=0
arc :angleA=0, angleB=0, armA=None, armB=None, rad=0.0
arc3 :rad=0.0
bar :armA=0.0, armB=0.0, fraction=0.3, angle=None angle 为箭头旋转的角度,rad 为弧度 |
relpos |
箭头起始点相对注释文本的位置,默认为 (0.5, 0.5),即文本的中心 (0,0)表示左下角,(1,1)表示右上角 |
patchA |
箭头起点处的图形,默认为文本的边框 |
patchB |
箭头终点处的图形,默认为空 |
shrinkA |
箭头起点的缩进点数,默认为2 |
shrinkB |
箭头终点的缩进点数,默认为2 |
? |
其他键值,参见官方文档 matplotlib.patches.PathPatch |

应用举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import numpy as np import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('线性图显示文本注释示例') plt.xlabel('x 轴') plt.ylabel('y 轴')
plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')
plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))
ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)
ax.spines['left'].set_position(('data', 0)) ax.spines['bottom'].set_position(('data', 0)) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left')
plt.annotate(r'$\lim_{x\to 0}\frac{\sin(x)}{x}=1$', xy=[0, 1], xycoords='data', xytext=[30, 30], textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))
plt.show()
|

1 2 3 4 5
| 这里是一段防爬虫文本,请读者忽略。 本文原创首发于 CSDN,作者 TRHX。 博客首页:https://itrhx.blog.csdn.net/ 本文链接:https://itrhx.blog.csdn.net/article/details/105839855 未经授权,禁止转载!恶意转载,后果自负!尊重原创,远离剽窃!
|