You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个已生成的matplotlib独立figure堆叠合并为3行2列的整体画布

Matplotlib合并多个独立Figure为3行2列布局的实现方法

Matplotlib没有提供直接合并已生成独立Figure的原生接口,你可以通过克隆原有Figure内所有绘图元素到新的目标Figure的方式实现需求,参考代码如下:

import matplotlib.pyplot as plt

# 创建3行2列的目标整体Figure,尺寸可按需调整
combined_fig, combined_axs = plt.subplots(3, 2, figsize=(20, 18))
# 按顺序整理已生成的源Figure
source_figs = [fig1, fig2, fig3]

for row, source_fig in enumerate(source_figs):
    # 获取当前源Figure的两个子坐标轴
    source_ax_list = source_fig.get_axes()
    for col, source_ax in enumerate(source_ax_list):
        target_ax = combined_axs[row][col]
        # 复制所有线图、折线、水平/垂直辅助线元素
        for line in source_ax.get_lines():
            target_ax.plot(
                line.get_xdata(), line.get_ydata(),
                color=line.get_color(),
                linestyle=line.get_linestyle(),
                linewidth=line.get_linewidth(),
                label=line.get_label()
            )
        # 复制所有散点元素
        for collection in source_ax.collections:
            if isinstance(collection, plt.PathCollection):
                offsets = collection.get_offsets()
                target_ax.scatter(
                    offsets[:, 0], offsets[:, 1],
                    s=collection.get_sizes(),
                    c=collection.get_facecolors(),
                    edgecolors=collection.get_edgecolors()
                )
        # 复制坐标轴配置、标题、标签、图例
        target_ax.set_title(source_ax.get_title())
        target_ax.set_xlabel(source_ax.get_xlabel())
        target_ax.set_ylabel(source_ax.get_ylabel())
        target_ax.set_xlim(source_ax.get_xlim())
        target_ax.set_ylim(source_ax.get_ylim())
        if source_ax.get_legend():
            target_ax.legend()

# 自动调整布局避免元素重叠
combined_fig.tight_layout()

# 后续可直接调用combined_fig完成展示、保存等操作
# combined_fig.show()
# combined_fig.savefig("merged_figure.png", dpi=300)

# 不需要保留原Figure的话可以关闭释放内存
# plt.close(fig1)
# plt.close(fig2)
# plt.close(fig3)

如果你用到了散点、折线、axhline之外的其他绘图元素(比如柱状图、注释、热力图等),只需要对应补充对应元素类型的克隆逻辑即可。

内容的提问来源于stack exchange,提问作者laszlopanaflex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:45:00