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()
MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.
The simplest legend can be created with the plt.legend() command, which automatically creates a legend for any labeled plot elements: import matplotlib.pyplot as plt plt. style. use('classic') %matplotlib inline import numpy as np.
To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With