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

如何设置Matplotlib全局图例与子图图例且子图图例不混入全局

解决Matplotlib全局图例包含子图独立图例标签的问题

下面提供两种实用的解决思路,帮你实现全局图例只显示指定内容、子图保留独立图例的需求:

方法1:给不需要全局显示的元素设置特殊标签

Matplotlib内置了特殊标签"_nolegend_",只要把元素的label设为这个值,全局图例就会自动忽略它。而子图的独立图例可以手动指定要展示的手柄和标签,完全不受影响。

修改后的代码示例:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1)

a = np.random.rand(5)
b = np.random.rand(5)
a1 = np.append(a, 0.5)
b1 = np.append(b, 0.5)

# 子图0的元素正常设置标签,会被全局图例收录
ax[0].plot(a, color='red', label='one')
ax[0].plot(b, color='blue', label='two')

# 子图1的元素设置特殊标签,避免被全局图例抓取
line1, = ax[1].plot(a1, color='red', label='_nolegend_')
line2, = ax[1].plot(b1, color='blue', label='_nolegend_')
# 手动给子图1创建独立图例
ax[1].legend(handles=[line1, line2], labels=['one appended', 'two appended'])

# 全局图例仅展示子图0的元素
fig.legend()

plt.show()

方法2:手动指定全局图例的手柄和标签

直接从目标子图(这里是子图0)中提取需要展示的手柄和标签,传给fig.legend(),这样全局图例就只会显示你指定的内容,不会自动收集所有带标签的元素。

修改后的代码示例:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1)

a = np.random.rand(5)
b = np.random.rand(5)
a1 = np.append(a, 0.5)
b1 = np.append(b, 0.5)

# 子图0的元素正常设置标签
ax[0].plot(a, color='red', label='one')
ax[0].plot(b, color='blue', label='two')

# 子图1正常设置标签并创建独立图例
ax[1].plot(a1, color='red', label='one appended')
ax[1].plot(b1, color='blue', label='two appended')
ax[1].legend()

# 从子图0获取手柄和标签,手动传给全局图例
handles, labels = ax[0].get_legend_handles_labels()
fig.legend(handles=handles, labels=labels)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:19:55