Dynamically add legends to matplotlib plots
Asked Answered
G

1

7

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()
Guild answered 28/4, 2013 at 16:1 Comment(9)
To me it's unclear what you're asking. What do you want to do that the above code doesn't achieve?Turmel
Im not able to get the 9 sets of legends that I need. Im getting just the last one. I even added the statement of matplotlib.pylab.hold(True)Guild
Are you sure that you don't want the legend call inside the loop?Apterous
What is the shape of s_A_approx?Turmel
No, not trying to call legend inside the loop. And the shape of s_A_approx is an array of 100 numbers ...Guild
I can't reproduce your problem. I had to adjust label=q to label=str(q), but after that, the plot and legend are produced as expected. Maybe see if you can provide here more of your script, like where s_A_approx comes from or an example of what s_A_approx looks like?Turmel
A is assembled by a method described in a paper. for q in range(1,10): A = (A*A.T)**q [U, s_A_approx, V] = numpy.linalg.svd(A) matplotlib.pylab.plot(s_A_approx, label = str(q)) matplotlib.pylab.legend(loc = 'upper left') matplotlib.pylab.show()Guild
and do you get all 9 legends to be shown or only the last one? Im still able to get only the last one..Guild
Here, I'll post an answer with my setupTurmel
T
10

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'
Turmel answered 29/4, 2013 at 0:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.