(Python)运行pylab.legend()命令时出错

时间:2013-03-24 16:40:19

标签: python matplotlib scatter-plot

我试图让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位

提前致谢...

1 个答案:

答案 0 :(得分: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()