import matplotlib.pyplot as plt
import numpy as np
# 生成一些示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# 创建一个2x2的子图布局
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# 在第一个子图上绘制sin(x)
axs[0, 0].plot(x, y1, label='sin(x)')
axs[0, 0].set_title('Sine Function')
axs[0, 0].legend()
# 在第二个子图上绘制cos(x)
axs[0, 1].plot(x, y2, label='cos(x)', color='green')
axs[0, 1].set_title('Cosine Function')
axs[0, 1].legend()
# 在第三个子图上绘制tan(x)(注意:tan(x)在某些点会趋于无穷大)
axs[1, 0].plot(x, y3, label='tan(x)', color='red')
axs[1, 0].set_title('Tangent Function')
axs[1, 0].legend()
# 在第四个子图上绘制sin(x)和cos(x)的叠加
axs[1, 1].plot(x, y1, label='sin(x)')
axs[1, 1].plot(x, y2, label='cos(x)', color='green')
axs[1, 1].set_title('Sine and Cosine Functions')
axs[1, 1].legend()
# 调整布局以防止子图重叠
plt.tight_layout()
# 显示图形
plt.show()
python画多个图
于 2024-10-29 18:38:45 首次发布