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

1 回答 1

10

我无法重现您的问题。通过对您的脚本进行一些调整,您所期望的对我有用。

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

结果图


如果有帮助,这是我的 matplotlib 版本:

>>> import matplotlib
>>> matplotlib.__version__
'1.0.1'
于 2013-04-29T00:18:11.243 回答