matplotlib 基本功能
??matplotlib 是 Python 的一个绘图库,使用它可以很方便地绘制出版质量级别的图形图片。本节主要介绍的是 matplotlib 的基本绘图功能,即在二维平面坐标系中绘制连续的曲线。
- 设置线型、线宽和颜色;
- 设置坐标轴的范围;
- 设置坐标刻度;
- 设置坐标轴;
- 图例;
- 特殊点;
- 备注;
matplotlib 基本功能详解
matplotlib.pyplot 绘图核心API
import numpy as np
import matplotlib.pyplot as plt
plt.plot(x_array, y_array)
plt.show()
案例:绘制一条正弦曲线
import numpy as np
import matplotlib.pyplot as plt
x_array = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y_array = np.sin(x_array)
plt.plot(x_array, y_array)
plt.savefig("sinx.jpg")
plt.show()
1、绘制水平线与垂直线
import numpy as np
import matplotlib.pyplot as plt
plt.vlines(xval, ymin, ymax, ...)
plt.hlines(yval, xmin, xmax, ...)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.vlines([-2, -1, 0, 1, 2], -1, 1, colors='blue')
plt.hlines(0, -3, 3, color='red')
plt.show()
图中绘制了 5 条垂直线( x = [-2, -1, 0, 1, 1], ymin = -1, ymax = 1 )和 1 条水平线( y = 0, xmin = -3, xmax = 3 ).
2、线型、线宽和颜色
-
线型:linestyle = [ ’ - ', ’ – ', ’ -. ', ’ : ’ ]; -
线宽:linewidth = 数字; -
颜色:color = 英文颜色单词 或 常用颜色的英文首字母 或 #495434 或 (56,54,20); -
透明度:alpha = 浮点数值;
比如:plt.plot(x_array, y_array, linestyle='--', linewidth=2, color='r', alpha=0.5)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
cosx = np.cos(x)
plt.plot(x, sinx, linestyle="-.", linewidth=2, color="dodgerblue", alpha=0.8)
plt.plot(x, cosx, linestyle='--', linewidth=2, color='orangered', alpha=1)
plt.savefig("cosx.png")
plt.show()
3、设置坐标轴范围
案例:以 sigmoid 函数为例,设置
x
x
x 轴和
y
y
y 轴的坐标轴范围
plt.xlim(x_limt_min, x_limt_max)
plt.ylim(y_limt_min, y_limt_max)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 1000)
y = 1/(1 + np.exp(-x))
plt.xlim(-8, 8)
plt.ylim(-0.01, 1.01)
plt.plot(x, y, linestyle='-', linewidth=2, color='red', alpha=0.8)
plt.show()
4、设置坐标刻度
案例:把正弦函数
y
=
s
i
n
x
y=sinx
y=sinx 的横坐标刻度设置为:0、
π
2
\dfrac{\pi}{2}
2π?、
π
\pi
π、
3
π
2
\dfrac{3\pi}{2}
23π? 和
2
π
2\pi
2π.
plt.xticks(x_val_list, x_text_list )
plt.yticks(y_val_list, y_text_list)
【推荐】:设置刻度值的时候,数值序列与文本序列的长度要一一对应且相同。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
x_val_list = [-np.pi, -1/2*np.pi, 0, 1/2*np.pi, np.pi]
x_text_list = [r'-$\pi$', r'-$\dfrac{\pi}{2}$', r'$0$', r'$\dfrac{\pi}{2}$', r'-$\pi$']
plt.xticks(x_val_list, x_text_list)
plt.plot(x, sinx, linestyle="-", linewidth=2, color="orangered", alpha=0.9)
plt.savefig("ysinx.jpg")
plt.show()
5、设置坐标轴
从上面绘制的曲线可以看到,坐标轴有上下左右,而实际绘制数学函数的图象时,我们的直角坐标系都是通过原点且相互垂直的。因此,matplotlib 设置有四个坐标轴名:left / right / top / bottom。
ax = plt.gca()
axis = ax.spines['坐标轴名']
axis.set_position((type, val))
axis.set_color(color)
例如:ax.spines['left'].set_position(('data', 0)) ,先获取到当前的坐标轴,然后设置坐标轴的位置或颜色值。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
plt.plot(x, sinx, linestyle='-.',linewidth=2, color='red', alpha=0.9)
x_val_list = [-np.pi, -1/2*np.pi, 0, 1/2*np.pi, np.pi]
x_text_list = [r'-$\pi$', r'-$\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'-$\pi$']
plt.xticks(x_val_list, x_text_list)
plt.yticks([-1, -0.5, 0.5, 1])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
plt.show()
6、图例
案例:显示两条曲线的图例,并测试 loc 属性;
设置图例的位置:loc : <关键字参数>制定图例的显示位置(如果不设置 loc,则显示默认位置)
plt.plot(x, y, ... label='', ...)
plt.legend(loc='')
Location String | Location Code |
---|
best | 0 | upper right | 1 | upper left | 2 | lower left | 3 | lower right | 4 | right | 5 | center left | 6 | center right | 7 | lower center | 8 | upper center | 9 | center | 10 |
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
cosx = 1/2 * np.cos(x)
plt.plot(x, sinx, linestyle='-.', linewidth=2, color='dodgerblue', label=r'$y=sin(x)$')
plt.plot(x, cosx, linestyle='--', linewidth=2, color='orangered', label=r'$y=\frac{1}{2}cos(x)$')
x_val_list = [-np.pi, -1/2*np.pi, 0, 1/2*np.pi, np.pi]
x_text_list = [r'-$\pi$', r'-$\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'-$\pi$']
plt.xticks(x_val_list, x_text_list)
plt.yticks([-1, -0.5, 0.5, 1])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.legend(loc='upper left')
plt.show()
7、特殊点
案例:绘制激活函数 sigmoid 曲线上的特殊点;
plt.scatter(xarray, yarray,
marker='',
s=70,
edgecolor='',
facecolor='',
zorder=3
)
说明:标注特殊点用到了 pyplot 的散点图绘制方法
Matplotlib Point 样式(marker 属性)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-20, 20, 1000)
y = 1/(1+np.exp(-x))
plt.plot(x, y, linestyle='-',linewidth=2, color='red', alpha=0.9, label=r'$\frac{1}{1+e^{-x}}$')
plt.yticks([0.5, 1])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
pointx = [0]
pointy = [0.5]
plt.scatter(pointx, pointy, marker='o', s=50, color='red', label='sample points',zorder=3)
plt.title(r"Function : $y=\dfrac{1}{1+e^{-x}}$")
plt.legend()
plt.show()
8、备注
案例:在某条曲线上的点添加备注,指明函数方程与值。
plt.annotate(
r'($\frac{\pi}{2}, 0)$',
xycoords='data',
xy=(x, y),
textcoords='offset points',
xytext=(x, y),
fontsize=14,
arrowprops=dict()
)
arrowprops = dict(
arrowstyle='->',
connectionstyle=''
)
个人觉得,arrowstyle 的参数很多,只需要记住 -> 就足够了。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
cosx = 1/2 * np.cos(x)
plt.plot(x, sinx, linestyle='-.', linewidth=2, color='dodgerblue', label=r'$y=sin(x)$')
plt.plot(x, cosx, linestyle='--', linewidth=2, color='orangered', label=r'$y=\frac{1}{2}cos(x)$')
x_val_list = [-np.pi, -1/2*np.pi, 0, 1/2*np.pi, np.pi]
x_text_list = [r'-$\pi$', r'-$\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'-$\pi$']
plt.xticks(x_val_list, x_text_list)
plt.yticks([-1, -0.5, 0.5, 1])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.legend(loc='upper left')
pointx = [np.pi / 2, np.pi / 2]
pointy = [1, 0]
plt.scatter(pointx, pointy, marker='o', s=50, color='red', label='sample points',zorder=3)
plt.annotate(
r'$(\frac{\pi}{2}, 1)$',
xycoords='data',
xy=(np.pi / 2, 1),
textcoords='offset points',
xytext=(50, 30),
fontsize=14,
arrowprops=dict(
arrowstyle='->',
connectionstyle='angle3'
)
)
plt.annotate(
r'$(\frac{\pi}{2}, 0)$',
xycoords='data',
xy=(np.pi / 2, 0),
textcoords='offset points',
xytext=(-50, -30),
fontsize=14,
arrowprops=dict(
arrowstyle='->',
connectionstyle='arc3'
)
)
plt.show()
|