导入matplotlib.pyplot包
import matplotlib.pyplot as plt
使用ax进行绘图
我们推荐使用ax进行绘图;
这样一个画布 figure (代码中的 fig )可以有多个子图像;
# 初始化整个画布,一个画布可以有若干子图
fig = plt.figure()
# 添加子图
ax1 = fig.add_subplot(1,1,1) # 1*1 的图像域,这个 ax1 是第 1 个子图像
#等价于:ax1 = fig.add_subplot(111)
fig, ax = plt.subplots() # 如果只有 1 个子图,也可以这么写
# 在子图上绘制曲线
ax1.plot(x, y, label="value of y", ls=':') # x,y 为自变量和因变量的列表
# ls: 线型,'-'实线; ':'虚线;'-.'点划线;
ax1.set(
xlim=[0.5, 4.5], # 设定 x 的定义域
ylim=[-2, 8], # 设定 y 的定义域
title='An Example Axes', # 设定子图的名称
xlabel='X-Axis',
ylabel='Y-Axis',
fontsize=40, # 字体大小
)
# 也可以通过以下命令实现对 x,y 轴名称的标注,子图赋名
ax1.set_xlim(-5,5)
ax1.set_ylim([-5,5])
ax1.set_xlabel('X-Axis')
ax1.set_ylabel('Y-Axis')
ax1.legend(title="figure of x & y", loc=1) # loc=1 代表图例在右上方
ax1.set_title('figure', fontsize=30)
# 显示画布与保存图像
# 子图显示网格
ax1.grid(True, color='green', axis='x',alpha=0.5)
# True 表示显示网格,green 表示网格颜色,axis 表示网格方向,alpha 表示明暗程度
plt.savefig("./figure.png") # 保存图像
plt.show() # 是否显示图像
此时在macOS和Linux系统下可保存为相对路径;
windows的vscode编辑器下保存为绝对路径;
可复用代码如下;
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
fig.set_size_inches(20.0, 10.0)
ax1.plot(x, y, label="value of y")
ax1.set_xlabel('X-Axis')
ax1.set_ylabel('Y-Axis')
ax1.legend(title="figure of x & y", loc=1)
ax1.grid(True,alpha=0.5)
plt.savefig("./figure.png",dpi=100)
plt.show()