Python: 如何在一个窗口显示两个 Matplotlib 图表
在 Python 中,可以使用 plt.subplot() 函数在一个窗口中显示多个图表。下面是一个示例代码:
import matplotlib.pyplot as plt
# 创建一个Figure对象
fig = plt.figure()
# 创建第一个子图
ax1 = fig.add_subplot(2, 1, 1) # 2行1列,第一个子图
ax1.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax1.set_title('Figure 1')
# 创建第二个子图
ax2 = fig.add_subplot(2, 1, 2) # 2行1列,第二个子图
ax2.plot([1, 2, 3, 4], [1, 8, 27, 64])
ax2.set_title('Figure 2')
# 显示两个子图
plt.show()
在上述代码中,我们首先使用 plt.figure() 函数创建一个 Figure 对象,然后使用 fig.add_subplot(nrows, ncols, index) 函数创建子图。参数 nrows 和 ncols 表示子图的行列数,index 表示子图的索引(从 1 开始)。
每个子图使用 ax.plot() 函数绘制图形,并使用 ax.set_title() 函数添加标题。最后,使用 plt.show() 函数显示所有子图。
通过这种方式,我们可以在一个窗口中显示多个图表,方便进行对比和分析。
原文地址: https://www.cveoy.top/t/topic/VTg 著作权归作者所有。请勿转载和采集!