Multiple legends in matplotlib in for loop
AFAIK, you need to call legend once, with all the arguments.
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().
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.
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. 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). 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.
[*] there are some exceptions on which artists it will pick up