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

如何将Matplotlib图表的Legend置于绘图区域之外?

卟啉描述符折线图:图例外置与X轴刻度隐藏实现

修改需求

  1. 将默认显示在绘图区域内的图例移至区域外
  2. X轴仅保留标签,隐藏刻度线

修改后的完整代码

import matplotlib.pyplot as plt

x = ['TPhP', 'TPrP', 'THP', 'OEP', 'Aristophyll A', 'TETMP', 'DMDHP', 'THDPP', 'BDTDP'] 
plt.xticks(range(len(x)), x, rotation='vertical')
# 隐藏X轴刻度线,保留标签
plt.tick_params(axis='x', bottom=False)
plt.ylim([-6, 12])

y1 = [-3.8681, -3.7851, -3.6178, -3.6749, -3.9103, -3.6640, -3.8450, -3.6096, -3.8354]
y2 = [3.8681, 3.7851, 3.6178, 3.6749, 3.9103, 3.6640, 3.8450, 3.6096, 3.8354]
y3 = [1.3510, 1.4613, 1.0980, 1.4572, 1.2272, 1.4408, 1.3334, 1.0898, 1.3783]
y4 = [0.3701, 0.3422, 0.4554, 0.3431, 0.4074, 0.3470, 0.3750, 0.4588, 0.3628]
y5 = [0.7402, 0.6843, 0.9108, 0.6863, 0.8148, 0.6940, 0.7500, 0.9176, 0.7256]
y6 = [10.1073, 10.4677, 7.1853, 9.8395, 9.3824, 9.6717, 9.8561, 7.0997, 10.1375]
y7 = [0.0925, 0.0854, 0.0926, 0.0815, 0.0986, 0.0817, 0.0923, 0.0926, 0.0903]
y8 = [0.1918, 0.1928, 0.1733, 0.1886, 0.1888, 0.1876, 0.1903, 0.1727, 0.1916]

plt.plot(x, y1, "-s", label="(ρ)/ eV")
plt.plot(x, y2, "-s", label="(χ)/ eV")
plt.plot(x, y3, "-s", label="(η)/ eV")
plt.plot(x, y4, "-s", label="(S)/ per eV")
plt.plot(x, y5, "-s", label="(σ)/ per eV")
plt.plot(x, y6, "-s", label="(ω)/ eV")
plt.plot(x, y7, "-s", label="(A)/ eV")
plt.plot(x, y8, "-s", label="(I)/ eV")

plt.ylabel("Descriptor values")
# 将图例移至绘图区外右上角,避免遮挡图表
plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)
# 调整右侧边距,确保图例完整显示
plt.subplots_adjust(right=0.8)

# 先保存图片再显示,避免保存空图
plt.savefig('Descriptors.png', bbox_inches='tight')
plt.show()

关键修改说明

  • X轴刻度隐藏:添加plt.tick_params(axis='x', bottom=False),指定隐藏X轴底部的刻度线,同时保留设置好的标签文本。
  • 图例外置:
    • 使用plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0),将图例定位在绘图区右上角外侧(bbox_to_anchor的坐标是相对于整个画布的比例),loc='upper left'让图例的左上角对齐锚点位置。
    • 添加plt.subplots_adjust(right=0.8)缩小绘图区右侧宽度,为图例预留显示空间;保存图片时加上bbox_inches='tight'确保图例被完整保存到图片中。
  • 修正保存顺序:将plt.savefig移至plt.show之前,因为plt.show会清空当前绘图画布,导致后续保存的图片为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:15:24