简体   繁体   English

Python 3.2 Matplotlib中为图添加图例的错误

[英]error of adding a legend for a plot in Python 3.2 Matplotlib

I need to add a legend for a plot in Python 3.2 Matplotlib. 我需要在Python 3.2 Matplotlib中为图添加图例。

But, the legend cannot be displayed after I added "black_dash" 但是,添加“ black_dash”后无法显示图例

My code: 我的代码:

   blue_line, = plt.plot([0, 1], [-3, -3], color='b', linestyle='-',    linewidth=1)

   black_dash, = plt.plot([0, 1], [-7, -7], color='k', linestyle='--', linewidth=1)

   plt.legend([blue_line, black_dash] , ["boundary of reg_zip", "lat/lon line"] , loc='upper center', bbox_to_anchor=(0.5, -0.5), \
           fancybox=True, shadow=True, ncol=5, fontsize=11)

The legend should have two lines and their explanations. 图例应包含两行及其说明。

UPDATE: 更新:

I need to polt a filled black circle in legend, But I got error: 我需要在图例中插入一个填充的黑色圆圈,但出现错误:

 File "C:\Python32\lib\site-packages\matplotlib\backends\backend_agg.py", line 146, in draw_path

self._renderer.draw_path(gc, path, transform, rgbFace)

**TypeError: float() argument must be a string or a number**

My code: 我的代码:

plt.plot([0, 1], [-3, -3], "ro", ms=10, mfc="k", mew=2, mec="k", label="boundary of reg_zip")

Thanks 谢谢

Here's what should work 这是应该工作的

plt.plot([0, 1], [-3, -3], color='b', linestyle='-', linewidth=1, label="blue line")
plt.plot([0, 1], [-7, -7], color='k', linestyle='--', linewidth=1, label="black dash")
plt.legend(loc='upper center', fancybox=True, shadow=True, ncol=5, fontsize=11)
plt.show()

So basically, add labels to lines, not legend, legend needs to recognize objects by name, and if you don't label them it can't (it will also automagically change the lines in the legend to fit the current look). 因此,基本上,在行中添加标签,而不是图例,图例需要通过名称识别对象,如果您不对它们进行标签,则图例就不能(这也会自动更改图例中的行以适合当前外观)。

Also always check your y axis range. 还请务必检查您的y轴范围。 It often tries to auto resize them, and with horizontal lines it often fails and places them at the very edge of the graph. 它经常尝试自动调整它们的大小,并且使用水平线经常会失败并将它们放置在图形的最边缘。 They're there you jsut can't see them! 它们在那里,您看不到它们!

EDIT 1: 编辑1:

Since I can see you're confused by this. 既然我能看到你对此感到困惑。 I made couple of plots. 我做了几个情节。 First one is of text (and generally any other box). 第一个是文本(通常是其他任何框)。 Second is of legends which position was determined by loc keyword. 其次是传说,其位置由loc关键字确定。 Third is of legends whose positions were determined by bbox_to_anchor . 第三是传说的立场由bbox_to_anchor确定。 Notice how the boxes for text don't correspond to boxes for legends. 请注意,文本框与图例框不对应。 Main reason is that bbox_to_anchor anchors upper right corner of the legend, while the text anchors lower left corner of the box. 主要原因是bbox_to_anchor锚定了图例的右上角,而文本锚定了框的左下角。

Also notice how the loc keyword doesn't depend on the graph scaling like bbox_to_anchor does. 还要注意loc关键字如何不像bbox_to_anchor那样取决于图形缩放。 To get rid of that nasty habit you have to declare a transformation for the bbox_to_anchor by doing 要摆脱这种讨厌的习惯,您必须通过执行以下操作为bbox_to_anchor声明一个转换:

plt.legend(bbox_to_anchor=(1, 1),
       bbox_transform=plt.gcf().transFigure)

as described in the legend manual . 图例手册中所述

Additionally, if your legend doesn't even fit within the gray plot area in the interactive plotting screen, you have to select the "Configure subplots" icon, and change the values until you can find your legend again. 此外,如果您的图例甚至不适合交互式绘图屏幕中的灰色图区域,则必须选择“配置子图”图标,然后更改值,直到可以再次找到图例。

文本框的位置

通过<code> loc </ code>关键字的图例位置

在此处输入图片说明

It's also important to realize that by adding loc keyword to a legend with bbox_to_anchor makes no difference at all. 同样重要的是要意识到,通过使用bbox_to_anchor向图例添加loc关键字bbox_to_anchor没有区别。 bbox_to_anchor will trample all other locations you provide the legend with. bbox_to_anchor将践踏您提供图例的所有其他位置。

Now far from the fact that I'm saying you shouldn't really meddle a lot into bbox_to_anchor option if you're not willing to read the manual and dabble deeper into matplotlib implementations, but I do suggest avoiding bbox_to_anchor in all cases except those when your graph is so overcrowded you have to place it outside. 现在,我要说的是,如果您不愿意阅读手册并更深入地研究matplotlib实现,那么您不应该真正介入bbox_to_anchor选项,但我确实建议在所有情况下都避免使用bbox_to_anchor ,您的图表太拥挤了,您必须将其放置在外面。 (in which case it's good time to consider graph design?) (在哪种情况下是考虑图形设计的好时机?)

In the end, here's the code for plotting graphs from above. 最后,这是从上方绘制图形的代码。

import matplotlib.pyplot as plt

plt.plot((0,0), (1,1), label="legend")

legends = []
for i in range(0, 11):
    legends.append(plt.legend([str(i)], loc=i))

for legend in legends:
    plt.gca().add_artist(legend)
#legends with loc=5 and 7 overlap
plt.show()


plt.plot((0,1), (0,1), label="legend")

legend1 = plt.legend(["0,0"], bbox_to_anchor=(0, 0))
legend3 = plt.legend(["1,1"], bbox_to_anchor=(1, 1))
legend2 = plt.legend(["0.5,0.5"], bbox_to_anchor=(0.5, 0.5))
legend4 = plt.legend(["0.5,0"], bbox_to_anchor=(0.5, 0))
legend6 = plt.legend(["0,0.5"], bbox_to_anchor=(0, 0.5))
legend5 = plt.legend(["1,0.5"], bbox_to_anchor=(1, 0.5))
legend7 = plt.legend(["0.5,1"], bbox_to_anchor=(0.5, 1))
legend8 = plt.legend(["1,0"], bbox_to_anchor=(1, 0))
legend9 = plt.legend(["0,1"], bbox_to_anchor=(0, 1))

plt.gca().add_artist(legend1)
plt.gca().add_artist(legend2)
plt.gca().add_artist(legend3)
plt.gca().add_artist(legend4)
plt.gca().add_artist(legend5)
plt.gca().add_artist(legend6)
plt.gca().add_artist(legend7)
plt.gca().add_artist(legend8)
plt.gca().add_artist(legend9)

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM