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

Matplotlib子图多元素图例与绘图重叠,如何设置避免重叠?

Matplotlib图例与绘图区域重叠的解决方法

创建Matplotlib子图时,若图例包含大量元素,常会出现与绘图区域重叠的问题。以下是几种实用的设置选项来解决该问题:

问题复现代码

import matplotlib.pyplot as plt
import numpy as np
 
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(nrows=2,ncols=1)

for i,axe in enumerate(ax):
    for j in range(10): 
        ax[i].plot(x, np.sin(x)+0.1*j, label="sin(x)")
    ax[i].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=7,ncol=4, mode="expand", borderaxespad=0.,fontsize = 10)
plt.tight_layout()
plt.show()

图例重叠效果:
图例重叠效果


可用解决设置选项

1. 调整bbox_to_anchor参数并手动预留子图空间

你当前使用的bbox_to_anchor=(0., 1.02, 1., .102)垂直偏移量不足,可增大偏移值,同时用subplots_adjust调整子图顶部间距:

import matplotlib.pyplot as plt
import numpy as np
 
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(nrows=2,ncols=1)

for i,axe in enumerate(ax):
    for j in range(10): 
        ax[i].plot(x, np.sin(x)+0.1*j, label="sin(x)")
    # 增大垂直偏移量,让图例远离子图顶部
    ax[i].legend(bbox_to_anchor=(0., 1.1, 1., .102), loc=7,ncol=4, mode="expand", borderaxespad=0.,fontsize = 10)
# 手动调整子图顶部区域,给图例留出空间
plt.subplots_adjust(top=0.85)
plt.show()

2. 将图例放在绘图区域外部

通过loc和bbox_to_anchor组合,把图例移到子图右侧、左侧或底部外部,完全避开绘图区域:

# 示例:将图例放在子图右侧外部
ax[i].legend(loc="upper left", bbox_to_anchor=(1,1), ncol=1, fontsize=10)

3. 使用constrained_layout自动布局

替代tight_layout,constrained_layout会智能调整子图和图例的位置,自动为图例预留空间:

# 创建子图时启用constrained_layout
fig, ax = plt.subplots(nrows=2,ncols=1, constrained_layout=True)

for i,axe in enumerate(ax):
    for j in range(10): 
        ax[i].plot(x, np.sin(x)+0.1*j, label="sin(x)")
    ax[i].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=7,ncol=4, mode="expand", borderaxespad=0.,fontsize = 10)
plt.show()

4. 优化图例自身布局

通过减小字体大小、增加列数让图例更紧凑,减少空间占用:

ax[i].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=7,ncol=5, mode="expand", borderaxespad=0.,fontsize=8)

5. 保存图片时确保图例完整(若需导出)

如果要保存图片,可将图例加入bbox_extra_artists,避免图例被裁剪:

# 先获取图例对象
legend = ax[i].legend(...)
# 保存时指定参数
fig.savefig("plot.png", bbox_extra_artists=[legend], bbox_inches='tight')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:47:23