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

如何为Matplotlib中重复标签的多曲线设置唯一图例

解决Matplotlib图例重复显示的问题

解决这个问题有两种简单直接的办法:

方法一:仅给同一地点的单条曲线设置标签

只给其中一组(比如bisque颜色的曲线)添加label参数,另一组曲线去掉label,这样图例只会生成一次对应标签的项。

修改后的代码:

import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.use('TkAgg')  # !IMPORTANT

fig, ax = plt.subplots()
# 第一组(bisque色)设置标签
ax.plot([93497, 137558, 158293, 180411, 183457, 187016, 189596],
        marker='.', linestyle='-', linewidth=0.5, label='Hong Kong', color="bisque")
ax.plot([67594, 112486, 130558, 149890, 157317, 163262, 165828],
        marker='v', linestyle='-', label='Kowloon', color="bisque")
ax.plot([58093, 102680, 121633, 138414, 144665, 149776, 152765],
        marker='*', linestyle='-', label='New Territories', color="bisque")

# 第二组(teal色)去掉label参数
ax.plot([101779, 140103, 160860, 176330, 183330, 182458, 184591],
        marker='.', markersize=5, linestyle='-', linewidth=0.5, color="teal")
ax.plot([81941, 115792, 131061, 147161, 153582, 160379, 161225],
        marker='v', markersize=5, linestyle='-', color="teal")
ax.plot([56305, 91942, 106554, 120067, 125490, 132070, 136451],
        marker='*', markersize=5, linestyle='-', color="teal")

ax.set_ylabel('$HKD/sq. m.')
ax.legend()
plt.show()

方法二:通过去重图例元素实现

如果已经给所有曲线都加了标签,不想逐个修改,可以先获取所有图例的元素,再通过字典去重(字典键唯一),最后生成去重后的图例。

修改后的代码:

import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.use('TkAgg')  # !IMPORTANT

fig, ax = plt.subplots()
ax.plot([93497, 137558, 158293, 180411, 183457, 187016, 189596],
        marker='.', linestyle='-', linewidth=0.5, label='Hong Kong', color="bisque")
ax.plot([67594, 112486, 130558, 149890, 157317, 163262, 165828],
        marker='v', linestyle='-', label='Kowloon', color="bisque")
ax.plot([58093, 102680, 121633, 138414, 144665, 149776, 152765],
        marker='*', linestyle='-', label='New Territories', color="bisque")

ax.plot([101779, 140103, 160860, 176330, 183330, 182458, 184591],
        marker='.', markersize=5, linestyle='-', linewidth=0.5, label='Hong Kong', color="teal")
ax.plot([81941, 115792, 131061, 147161, 153582, 160379, 161225],
        marker='v', markersize=5, linestyle='-', label='Kowloon', color="teal")
ax.plot([56305, 91942, 106554, 120067, 125490, 132070, 136451],
        marker='*', markersize=5, linestyle='-', label='New Territories', color="teal")

ax.set_ylabel('$HKD/sq. m.')

# 获取所有图例的handles和labels
handles, labels = ax.get_legend_handles_labels()
# 用字典去重,保留首次出现的标签对应的图例元素
unique_items = dict(zip(labels, handles))
# 生成去重后的图例
ax.legend(unique_items.values(), unique_items.keys())

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:00:20