如何通过plt.subplots(1,2)并排绘制已获取的两个matplotlib Figure对象
如何将已生成的Matplotlib绘图对象并排展示
当无法访问原始绘图数据时,我们可以通过复制原有绘图中的元素到新的子图布局中,实现将两个独立的fig对象并排展示的效果,具体步骤如下:
核心思路
把原有绘图坐标轴(Axes)中的可视化元素(如线条、标记等)复制到新创建的子图中,同时同步原坐标轴的范围、标签、标题等属性,保证展示效果与原绘图一致。
实现代码
import matplotlib.pyplot as plt import numpy as np # 执行用户提供的代码生成目标绘图对象 x = np.linspace(-5, 5, 11) y = x y_2 = x * x plt.plot(x,y) fig_1 = plt.gcf() ax_1 = plt.gca() plt.close() # 关闭原画布,避免干扰后续绘图 plt.plot(x,y_2) fig_2 = plt.gcf() ax_2 = plt.gca() plt.close() # 创建1行2列的新子图布局 fig, (new_ax1, new_ax2) = plt.subplots(1, 2, figsize=(10, 4)) # 复制第一个绘图的元素到新子图 for artist in ax_1.get_children(): if isinstance(artist, plt.Line2D): new_line = artist.copy() new_ax1.add_artist(new_line) # 同步原坐标轴的属性 new_ax1.set_xlim(ax_1.get_xlim()) new_ax1.set_ylim(ax_1.get_ylim()) new_ax1.set_xlabel(ax_1.get_xlabel()) new_ax1.set_ylabel(ax_1.get_ylabel()) new_ax1.set_title("y = x") # 可自定义标题,或用ax_1.get_title() # 复制第二个绘图的元素到新子图 for artist in ax_2.get_children(): if isinstance(artist, plt.Line2D): new_line = artist.copy() new_ax2.add_artist(new_line) # 同步原坐标轴的属性 new_ax2.set_xlim(ax_2.get_xlim()) new_ax2.set_ylim(ax_2.get_ylim()) new_ax2.set_xlabel(ax_2.get_xlabel()) new_ax2.set_ylabel(ax_2.get_ylabel()) new_ax2.set_title("y = x²") # 自动调整布局,避免标签重叠 plt.tight_layout() plt.show()
扩展说明
- 如果原绘图包含其他类型的元素(如散点、文本、图例等),可根据对应的类型(如
ScatterCollection、Text)在遍历中添加判断,复制相应元素。 plt.close()用于关闭原始绘图的画布,防止后续出现多余的绘图窗口,若保留原画布可注释该行。
内容的提问来源于stack exchange,提问作者Sergey Bushmanov
相关产品推荐
相关产品推荐

