【问题标题】:(Python) Error running the pylab.legend() command(Python) 运行 pylab.legend() 命令时出错
【发布时间】:2013-03-24 16:40:19
【问题描述】:

我正在尝试让 legend() 命令工作,但徒劳无功,当我运行下面的代码时,在调用 pl.legend() 的行中出现以下错误:

    AttributeError                            Traceback (most recent call last)
<ipython-input-226-5b8a32c5300f> in <module>()
----> 1 leg = pl.legend(numpoints=3)

/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in legend(*args, **kwargs)
   2798 @docstring.copy_dedent(Axes.legend)
   2799 def legend(*args, **kwargs):
-> 2800     ret =  gca().legend(*args, **kwargs)
   2801     draw_if_interactive()
   2802     return ret

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in legend(self, *args, **kwargs)
   4482 
   4483         if len(args)==0:
-> 4484             handles, labels = self.get_legend_handles_labels()
   4485             if len(handles) == 0:
   4486                 warnings.warn("No labeled objects found. "

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in get_legend_handles_labels(self, legend_handler_map)
   4317             label = handle.get_label()
   4318             #if (label is not None and label != '' and not label.startswith('_')):
-> 4319             if label and not label.startswith('_'):
   4320                 handles.append(handle)
   4321                 labels.append(label)

AttributeError: 'int' object has no attribute 'startswith'

代码,

    import numpy as np
    import pylab as pl
    x = np.linspace(0, 2*np.pi, 100)
    pl.plot(x, np.sin(x), "-x", label=u"sin")
    pl.plot(x, np.random.standard_normal(len(x)), 'o', label=u"rand")
    leg = pl.legend(numpoints=3)

这很奇怪,因为对其他人来说它似乎工作正常。我正在使用 Python 64 位

提前谢谢...

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    你真的需要pylab吗?

    import numpy as np
    #import pylab as pl
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2*np.pi, 100)
    plt.plot(x, np.sin(x), "-x", label=u"sin")
    plt.plot(x, np.random.standard_normal(len(x)), 'o', label=u"rand")
    leg = plt.legend(numpoints=3)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2014-08-01
      • 2016-11-11
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      相关资源
      最近更新 更多