python绘图时如何添加图例_关于python:在matplotlib中的图例中重复项目?

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

1

2

3

4

5

6

7

8

9

10import 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()

我结束了这个情节

g3QQH.jpg

显然,项目在图中重复。 我该如何纠正该错误?

这不是错误,它添加了许多重复的条目,因为标签是相同的。 如果必须在for循环内更改标签...

这是对您的问题的一个很好的答案:stackoverflow.com/questions/13588920/

正如文档所说,尽管很容易错过:

If label attribute is empty string or starts with"_", those artists

will be ignored.

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

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

其中i是我的循环索引。

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

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

很好的见识。 i == 0确实可以解决问题。但是散点不能通过i == 0来解决,因为它不在循环中。我如何才能使其变得完美? i.stack.imgur.com/B3osh.jpg

@mavErick:对不起,我没有关注。图例中仅存在一个Intersections行。

对,就是这样。但是,为什么我的传说中有三个红点?不应该只有一个吗?

@macErick:啊,那完全是另一个问题。那只是一个奇怪的matplotlib约定。在这里查看我的答案:您可以改为使用axes.legend(scatterpoints=1)来更改数字。

太棒了!问题解决了。但老实说,我很喜欢这个答案的说明方式。但这会导致错误。如果错误可以解决,对我来说似乎更"标准"。

好吧,您可以自由地做自己喜欢的事。 :^)如果您使用rep[0]而不是rep,则该方法应该有效。 plot和scatter具有不同形状的返回值。

谢谢,你是一个传奇。

这是在正常分配标签后删除重复的图例条目的方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20representatives=[[[-100,40],[-50,20],[0,0],[75,-5],[100,5]], #made up some data

[[-60,80],[0,85],[100,90]],

[[-60,15],[-50,90]],

[[-2,-2],[5,95]]]

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')

#make sure only unique labels show up (no repeats)

handles,labels=axes.get_legend_handles_labels() #get existing legend item handles and labels

i=arange(len(labels)) #make an index for later

filter=array([]) #set up a filter (empty for now)

unique_labels=tolist(set(labels)) #find unique labels

for ul in unique_labels: #loop through unique labels

filter=np.append(filter,[i[array(labels)==ul][0]]) #find the first instance of this label and add its index to the filter

handles=[handles[int(f)] for f in filter] #filter out legend items to keep only the first instance of each repeated label

labels=[labels[int(f)] for f in filter]

axes.legend(handles,labels) #draw the legend with the filtered handles and labels lists

结果如下:

eTdMa.png

左边是上面脚本的结果。在右侧,图例调用已替换为axes.legend()。

好处是您可以遍历大多数代码,而通常只分配标签,而不必担心内联循环或if。您也可以将其构建为图例或类似内容的包装。

为此,它提供了一种快速修复方法,而无需修改添加行后的逻辑。

根据EL_DON的回答,这是一种绘制没有重复标签的图例的常规方法:

1

2

3

4def legend_without_duplicate_labels(ax):

handles, labels = ax.get_legend_handles_labels()

unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]

ax.legend(*zip(*unique))

用法示例:(在repl.it中打开)

1

2

3

4

5

6

7

8fig, ax = plt.subplots()

ax.plot([0,1], [0,1], c="y", label="my lines")

ax.plot([0,1], [0,2], c="y", label="my lines")

legend_without_duplicate_labels(ax)

plt.show()

b0TP4.png

它对我有用,我必须使用此stackoverflow.com/a/50947068/9020163在唯一列表中对项目进行排序

按字母顺序排列标签?

究竟。我为路径的不同"高度"使用不同的颜色。该线的每个线段可以在相同高度上进行多次,因此图例显示了多次在同一高度上输入。删除重复项会使值混乱。

这不是错误。您在for循环中的标签将len(representatives)-1重复标签添加到图例中。如果您做了类似的事情怎么办

1

2

3

4for i, representative in enumerate(representatives):

rep, = axes.plot([e[0] for e in representative], [e[1] for e in representative], color='b')

inter = axes.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r')

axes.legend((rep, inter), ("Representatives","Intersections"))

编辑:以下代码的格式使用matplotlib图例教程上发布的格式。上面的代码失败的原因是因为rep, =之后缺少逗号。每次迭代rep都会被覆盖,并且当用于调用legend时,只有最后一个代表图存储在rep中。

1

2

3

4

5

6fig = plt.figure()

ax = fig.add_subplot(111)

for i, representative in enumerate(representatives):

rep, = ax.plot([e[0] for e in representative], [e[1] for e in representative], color='b')

inter = ax.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r')

ax.legend((rep, inter), ("Representatives","Intersections"))

您也可以尝试按照在OP中的方式绘制数据,但可以使用

1handles, labels = ax.get_legend_handles_labels()

并编辑handles和labels的内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值