24

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

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
brain storm
  • 30,124
  • 69
  • 225
  • 393

2 Answers2

34
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

tacaswell
  • 84,579
  • 22
  • 210
  • 199
10

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.

Laura Huysamen
  • 398
  • 3
  • 9
  • you don't need to pull the labels out by hand, it will do that for you. The `%` notation will be taken out of the language eventually but it has a huge install base (in the standard library no less) and will take a long time to expunge. – tacaswell Feb 12 '13 at 05:56
  • Indeed you are correct, I just happened to have it that way because I had multiple axes in that piece of code. See [this](http://stackoverflow.com/questions/5484922/secondary-axis-with-twinx-how-to-add-to-legend?rq=1) question. Thanks for reminding me about the %! – Laura Huysamen Feb 12 '13 at 06:05