Matplotlib 如何把图例放到图表外面
plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) 把图例放到绘图区右侧外部;配合 tight_layout 或 subplots_adjust 防止图例被裁掉。附右侧、下方两种常用布局代码。
一句话回答:用 bbox_to_anchor 参数:plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) 把图例锚定到绘图区右上角之外。坐标是轴坐标系**(0-1 相对于绘图区),x=1 就是右边界。图例被画布裁掉时加 plt.tight_layout() 或保存时用 bbox_inches='tight'。**
放在右侧(最常用)
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [2, 4, 3]
y2 = [1, 3, 5]
plt.plot(x, y1, label='Series 1')
plt.plot(x, y2, label='Series 2')
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.tight_layout() # 关键:为图例腾出画布空间
plt.show()
loc='upper left' 指图例框的左上角锚定在 (1, 1)——即轴的右上角,于是整个图例自然落在绘图区右侧。
放在下方
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.08), ncol=3)
plt.tight_layout()
(0.5, -0.08) = 水平居中、轴下边界往下 8%;ncol=3 让图例横向排 3 列,适合图例项多的情况。
保存图片时图例被裁掉
tight_layout() 调整 Figure 布局,也影响保存结果,并非只作用于屏幕。尺寸、布局或被排除在布局计算之外的 artist 仍可能导致裁切。保存时可使用:
plt.savefig('chart.png', bbox_inches='tight', dpi=150)
bbox_inches='tight' 按参与边界计算的 artist 调整输出边界;自定义 artist 必要时需传入 bbox_extra_artists。应在 plt.show() 前保存,或保留 Figure 引用调用 fig.savefig()。
参数坐标速查
| 想要的位置 | loc | bbox_to_anchor |
|---|---|---|
| 右侧外 | upper left |
(1, 1) |
| 下方外 | upper center |
(0.5, -0.08) |
| 上方外 | lower center |
(0.5, 1.02) |
| 左侧外 | upper right |
(-0.05, 1) |
常见问题(FAQ)
Q:subplot 多子图怎么放一个公共图例?
A:创建 fig, axs = plt.subplots(..., layout='constrained') 后,用 fig.legend(handles, labels, loc='outside right center')(Matplotlib 3.7+,需先收集 handles/labels;constrained layout 为外侧图例预留空间);老版本手工收集各子图的 handles 再 fig.legend(..., bbox_to_anchor=(1, 0.5))。
Q:图例挡住了数据怎么办?
A:两条路:放外部(本文方案);或换位置 loc='best' 让 Matplotlib 自动找空白区域。数据密集时放外部最干净。
Q:右侧图例占太宽导致图被压扁?
A:tight_layout() 后手动微调:plt.subplots_adjust(right=0.75) 给右侧留 25% 空间;或把图例换到下方用多列布局。
核查依据
本文依据官方文档核对,示例未在实际业务环境运行;上线前请按部署版本、权限与数据范围验证。