【问题标题】:Dynamically add legends to matplotlib plots in python在 python 中动态地将图例添加到 matplotlib 图中
【发布时间】:2013-04-22 07:10:23
【问题描述】:

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

【问题讨论】:

  • 对我来说,不清楚你在问什么。你想做什么上面的代码没有实现?
  • 我无法获得我需要的 9 组图例。我得到的只是最后一个。我什至添加了matplotlib.pylab.hold(True)的声明
  • 您确定不希望legend 调用inside 循环吗?
  • s_A_approx的形状是什么?
  • 不,不尝试在循环内调用图例。 s_A_approx 的形状是一个 100 个数字的数组 ...

标签: python matplotlib plot enthought


【解决方案1】:

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

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多