通过访问matplotlib画廊(https://matplotlib.org/),可以看到众多使用matplotlib绘制的图表 有线图、折线图、直方图、饼图、散点图等等
1.分别使用OO模式和pyplot绘制一个sin函数
#显式创建fig,ax绘制
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0,2.0,0.01)
y = np.sin(2 * np.pi * x)
fig,ax = plt.subplots()
ax.plot(x,y)
ax.set(xlabel = 'x label',ylabel = 'y label',
title = 'About as simple as it gets, folks')
ax.grid()
fig.savefig("test1.png")
plt.show()
#使用pyplot绘制,pyplot自动创建fig,ax
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0,2.0,0.01)
y = np.sin(2 *np.pi * x)
plt.plot(x,y)
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('About as simple as it gets, folks')
plt.grid()
plt.savefig("test2.png")
plt.show()
两种方法所绘制的图如下:
2.绘制多个子图
这种情况下,选择使用OO模式,显式创建figure和axes
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
#创建两个子图
fig, (ax1, ax2) = plt.subplots(2, 1)
fig.suptitle('A tale of 2 subplots')
ax1.plot(x1, y1, 'o-')
ax1.set_ylabel('Damped oscillation')
ax2.plot(x2, y2, '.-')
ax2.set_xlabel('time (s)')
ax2.set_ylabel('Undamped')
plt.savefig("test3.png")
plt.show()
参考资料: