python图例重复显示_停止matplotlib在图例中重复标签

当在matplotlib图表中多次使用相同标签时,图例会重复显示。解决这个问题的一种方法是在调用`legend`函数时,先将标签和图例处理成有序字典,以消除重复。对于Python 3.7以下版本,可以使用`OrderedDict`,而3.7及以上版本则直接使用字典即可。
摘要由CSDN通过智能技术生成

Here is a very simplified example:

xvalues = [2,3,4,6]

for x in xvalues:

plt.axvline(x,color='b',label='xvalues')

plt.legend()

The legend will now show 'xvalues' as a blue line 4 times in the legend.

Is there a more elegant way of fixing this than the following?

for i,x in enumerate(xvalues):

if not i:

plt.axvline(x,color='b',label='xvalues')

else:

plt.axvline(x,color='b')

解决方案

plt.legend takes as parameters

A list of axis handles which are Artist objects

A list of labels which are strings

These parameters are both optional defaulting to plt.gca().get_legend_handles_labels().

You can remove duplicate labels by putting them in a dictionary before calling legend. This is because dicts ca

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值