简体   繁体   English

for循环中matplotlib中的多个图例

[英]Multiple legends in matplotlib in for loop

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

在此处输入图片说明

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 legend works, each time it is called it destroys the current legend and replaces it with the new one.您遇到了legend工作方式,每次调用它都会破坏当前的图例并用新的图例替换它。 If you only give legend a list of strings it iterates through the artists (the objects that represent the data to be drawn) in the axes until it runs out of labels (hence why your first curve is labeled as the 4th).如果你只给legend一个字符串列表,它会遍历axes的艺术家(代表要绘制数据的对象),直到用完标签(因此为什么你的第一条曲线被标记为第四条)。 If you include the kwarg label in the plot command, when you call legend with out any arguments, it will iterate through the artists* and generate legend entries for the artists with labels.如果在plot命令中包含kwarg label ,当您不带任何参数调用legend时,它将遍历艺术家*并为带有标签的艺术家生成图例条目。

[*] there are some exceptions on which artists it will pick up [*] 它会选择哪些艺术家有一些例外

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.如果您有单独的轴(例如 twinx),这也将起作用,并且所有图例信息都将通过一个图例显示。 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.顺便说一句,我似乎记得 % 符号很旧,人们应该更喜欢 str.format(),但恐怕我不记得为什么了。

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

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