import matplotlib.pyplot as plt
import numpy as np
figure对象,类似于绘画的画布
# 首先创建figure对象(类似画布)
fig = plt.figure()
print(fig) # 默认大小是640*480像素
# 可以对其进行自定义设置,1000*800的像素,每个点的分辨率像素是120
fig = plt.figure(figsize=(10,8), dpi=120)
1.直接在figure上绘制所需图形
# 新建数组
arr = np.random.randn(1000)
# 将数组数据加载到画布中并保存显示
plt.plot(arr)
plt.savefig("fig1.png")
plt.show()
得到如下图片
2.对figure进行分割,在子图上进行绘图
# 对画布进行分割为2*2的四块子图,第三个参数表示子图编号
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
# 将数据加载到子图中并保存显示
ax2.plot(arr)
plt.savefig("fig2.png")
plt.show()
得到如下图片(注意运行这部分代码需要将上一部分中的plt.show()注释掉,因为画布一旦进行显示,就无法再次保存,所以.show()方法一般是放在最后)
常见的绘图方式
1.直方图--plt.his