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

Python matplotlib多子图添加全局图例后出现重叠如何调整

解决方案

1. 图例与绘图区域重叠修复

tight_layout()默认不会给全局图例预留绘制空间,可通过两种方式适配:

  • 内置图例:调整fig.tight_layout()的rect参数限制子图绘制范围,给底部/侧边预留图例空间
  • 外置图例:通过bbox_to_anchor将图例锚定到画布外侧,同步调整子图范围避免裁切

2. 折线互相遮挡修复

可通过三个维度优化线条区分度:

  • 调整zorder层级:需要优先显示的折线设置更大的zorder值,数值越高层级越靠上
  • 添加透明度:给折线设置0.6-0.8的alpha值,重叠区域可透出下层线条
  • 差异化样式:给不同折线设置不同的线型、线宽,就算重叠也可直观区分

修改后完整代码

fig, axes = plt.subplots(n, m, figsize=(15, 8))
for var, ax in zip(vars_to_plot, axes.flat):
    for idx, solution in enumerate(solutions):
        ax.plot(
            solution.summary_variables["Cycle number"],
            solution.summary_variables[var],
            label=f"this is plot {idx+1}",
            zorder=2 if idx == 1 else 1,  # 假设第二条是需要上层显示的红色折线
            alpha=0.8,
            linestyle="-" if idx == 0 else "--"
        )
    ax.set_xlabel("Cycle number")
    ax.set_ylabel(var)
    ax.set_xlim([1, solution.summary_variables["Cycle number"][-1]])

# 底部预留0.08比例空间放置图例,rect参数格式为(左边界, 下边界, 右边界, 上边界)
fig.tight_layout(rect=(0, 0.08, 1, 1))
# 全局图例设置,ncol设为2可减少横向占用
fig.legend(loc="lower center", bbox_to_anchor=(0.5, 0.01), ncol=2)

# 保存时添加bbox_inches参数避免图例被裁切
plt.savefig("plot.png", dpi=300, bbox_inches="tight")

如果需要将图例放在画布右侧外部,可替换上述布局和图例配置为:

fig.tight_layout(rect=(0, 0, 0.85, 1))
fig.legend(loc="center left", bbox_to_anchor=(0.87, 0.5))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:21:04