Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add legends to matplotlib plots in python

I have a set of plots in python and want to add legends to each of them separately. I am generating the plots in a for loop and want to add the legends dynamically.

Im getting only the last legend shown. I want all 9 off them to be displayed

for q in range(1,10):
      matplotlib.pylab.plot(s_A_approx, label = q)
matplotlib.pylab.legend(loc = 'upper left')
matplotlib.pylab.show()
like image 271
computationally_curious Avatar asked Apr 28 '13 16:04

computationally_curious


1 Answers

I can't reproduce your problem. With a few adjustments to your script, what you're expecting is working for me.

import matplotlib.pylab
import numpy as np

for q in range(1,10):
    # create a random, 100 length array
    s_A_approx = np.random.randint(0, 100, 100)
    # note I had to make q a string to avoid an AttributeError when 
    # initializing the legend
    matplotlib.pylab.plot(s_A_approx, marker='.', linestyle='None', label=str(q))

matplotlib.pylab.legend(loc='upper left')
matplotlib.pylab.show()

resulting plot


If it helps, here's my matplotlib version:

>>> import matplotlib
>>> matplotlib.__version__
'1.0.1'
like image 83
drs Avatar answered Oct 14 '22 17:10

drs