Python for循环中matplotlib中的多个图例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14826119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple legends in matplotlib in for loop
提问by brain storm
The following program executes fine but only one legend is displayed. How can I have all the four legends displayed? kindly see the image attached.
下面的程序运行良好,但只显示一个图例。我怎样才能显示所有四个图例?请参阅所附图片。
import matplotlib.pyplot as plt
dct = {'list_1' : [1,2,4,3,1],'list_2' : [2,4,5,1,2],'list_3' : [1,1,3,4,6],'list_4' : [1,1,2,2,1]}
xs = [0,1,2,3,4]
for i in [1,2,3,4]:
plt.plot(xs,dct['list_%s' %i])
plt.legend(['%s data' %i])
plt.show()


采纳答案by tacaswell
import matplotlib.pyplot as plt
dct = {'list_1' : [1,2,4,3,1],'list_2' : [2,4,5,1,2],'list_3' : [1,1,3,4,6],'list_4' : [1,1,2,2,1]}
xs = [0,1,2,3,4]
for i in [1,2,3,4]:
plt.plot(xs,dct['list_%s' %i], label='%s data' % i)
plt.legend()
plt.show()
You are running up against the way that legendworks, each time it is called it destroys the current legend and replaces it with the new one. If you only give legenda list of strings it iterates through the artists (the objects that represent the data to be drawn) in the axesuntil it runs out of labels (hence why your first curve is labeled as the 4th). If you include the kwarglabelin the plotcommand, when you call legendwith out any arguments, it will iterate through the artists* and generate legend entries for the artists with labels.
您遇到了legend工作方式,每次调用它都会破坏当前的图例并用新的图例替换它。如果你只给出legend一个字符串列表,它会遍历艺术家(代表要绘制数据的对象),axes直到它用完标签(因此你的第一条曲线被标记为第四条)。如果您kwarglabel在plot命令中包含,当您不legend带任何参数调用时,它将遍历艺术家 * 并为带有标签的艺术家生成图例条目。
[*] there are some exceptions on which artists it will pick up
[*] 它会选择哪些艺术家有一些例外
回答by Laura Huysamen
AFAIK, you need to call legend once, with all the arguments.
AFAIK,您需要使用所有参数调用图例一次。
import matplotlib.pyplot as plt
dct = {'list_1' : [1,2,4,3,1],'list_2' : [2,4,5,1,2],
'list_3' : [1,1,3,4,6],'list_4' : [1,1,2,2,1]}
xs = [0,1,2,3,4]
lines = []
for i in range(1,5):
lines += plt.plot(xs,dct['list_%s' %i], label="{} data".format(i))
Note that I have included the label here as one of the arguments to the plot function, so that later we can call get_label().
请注意,我在此处包含了标签作为 plot 函数的参数之一,以便稍后我们可以调用 get_label()。
labels = [l.get_label() for l in lines]
plt.legend(lines, labels)
plt.show()
This will also work if you have separate axes (such as twinx), and all of the legend information will come through on one legend. By the way, I seem to recall that the % notation is old and one should prefer str.format(), but I'm afraid I can't remember why.
如果您有单独的轴(例如 twinx),这也将起作用,并且所有图例信息都将通过一个图例显示。顺便说一句,我似乎记得 % 符号很旧,人们应该更喜欢 str.format(),但恐怕我不记得为什么了。

