动态地将图例添加到python中的matplotlib图中

时间:2013-04-28 16:01:20

标签: python matplotlib plot enthought

我在python中有一组图,并希望分别为每个图添加图例。我在for循环中生成绘图,并希望动态添加图例。

我只获得了显示的最后一个传奇。我希望它们全部显示9个

for q in range(1,10):
      matplotlib.pylab.plot(s_A_approx, label = q)
matplotlib.pylab.legend(loc = 'upper left')
matplotlib.pylab.show()

1 个答案:

答案 0 :(得分:9)

我无法重现你的问题。通过对脚本进行一些调整,您期望的是为我工作。

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


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

>>> import matplotlib
>>> matplotlib.__version__
'1.0.1'
相关问题