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()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 1
    To me it's unclear what you're asking. What do you want to do that the above code doesn't achieve? – drs Apr 28 '13 at 16:23
  • 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)` – computationally_curious Apr 28 '13 at 16:25
  • Are you sure that you don't want the `legend` call *inside* the loop? – Brent Bradburn Apr 28 '13 at 16:30
  • What is the shape of `s_A_approx`? – drs Apr 28 '13 at 16:42
  • No, not trying to call legend inside the loop. And the shape of s_A_approx is an array of 100 numbers ... – computationally_curious Apr 28 '13 at 22:41
  • 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? – drs Apr 28 '13 at 23:39
  • 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()` – computationally_curious Apr 28 '13 at 23:49
  • and do you get all 9 legends to be shown or only the last one? Im still able to get only the last one.. – computationally_curious Apr 29 '13 at 00:05
  • Here, I'll post an answer with my setup – drs Apr 29 '13 at 00:17

1 Answers1

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'
drs
  • 5,679
  • 4
  • 42
  • 67