几种方式
1. pyplot 方式 (面向过程)
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro-', label='平方')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('简单折线图')
plt.legend()
plt.show()
2. 面向对象方式 (OO风格)
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot([1, 2, 3, 4], [1, 4, 9, 16], 'bo--', label='平方')
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_title('面向对象绘图')
ax.legend()
plt.show()
3. 多子图绘制
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
x = np.linspace(0, 2*np.pi, 100)
axes[0, 0].plot(x, np.sin(x), 'r-')
axes[0, 0].set_title('正弦函数')
axes[0, 1].plot(x, np.cos(x), 'g--')
axes[0, 1].set_title('余弦函数')
axes[1, 0].plot(x, np.tan(x), 'b:')
axes[1, 0].set_title('正切函数')
axes[1, 1].plot(x, np.exp(x), 'y-.')
axes[1, 1].set_title('指数函数')
plt.tight_layout()
plt.show()