matplotlib中图例中的重复项? [英] Duplicate items in legend in matplotlib?

查看:262
本文介绍了matplotlib中图例中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下代码段将图例添加到我的绘图中:

I am trying to add the legend to my plot with this snippet:

import matplotlib.pylab as plt

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.set_xlabel('x (m)')
axes.set_ylabel('y (m)')
for i, representative in enumerate(representatives):
    axes.plot([e[0] for e in representative], [e[1] for e in representative], color='b', label='Representatives')
axes.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r', label='Intersections')
axes.legend()   

我最终得到了这个情节

很明显,这些项目在地图中是重复的.我该如何纠正该错误?

Obviously, the items are duplicated in the plot. How can I correct this error?

推荐答案

正如文档所述,尽管很容易小姐:

As the docs say, although it's easy to miss:

如果label属性为空字符串或以"_"开头,则这些艺术家 将被忽略.

If label attribute is empty string or starts with "_", those artists will be ignored.

因此,如果我要在循环中绘制相似的线条,而我只想在图例中显示一条示例线,我通常会做类似的事情

So if I'm plotting similar lines in a loop and I only want one example line in the legend, I usually do something like

ax.plot(x, y, label="Representatives" if i == 0 else "")

其中i是我的循环索引.

where i is my loop index.

看起来不像分别构建它们那样好看,但是我经常想使标签逻辑尽可能地接近线图.

It's not quite as nice to look at as building them separately, but often I want to keep the label logic as close to the line drawing as possible.

(请注意,matplotlib开发人员本身倾向于使用"_nolegend_"来明确表示.)

(Note that the matplotlib developers themselves tend to use "_nolegend_" to be explicit.)

这篇关于matplotlib中图例中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆