绘制一些数据时出现python matplotlib错误

时间:2012-10-25 03:33:10

标签: python numpy matplotlib

我正在尝试绘制一些数据,但是我从标注的行中得到了这个错误。我用谷歌搜索了这条线,但在这个问题上找不到任何有意义的讨论。我是Python的新手,所以当我继续使用时,我试图弄清楚这些东西。

 pl.figure()
 ax = pl.subplot(111)
 ax.plot(Xk[:,0], Xk[:,1], '.')

 ERROR=>>> twos = (y == 2).nonzero()[0]
 for i in twos:
    imagebox = OffsetImage(X[i,:].reshape(28,28))
    location = Xk[i,0], Xk[i,1]
    ab = AnnotationBbox(imagebox, location, boxcoords='data', pad=0.)
    ax.add_artist(ab)

 pl.show()

这是错误消息

 AttributeError: 'bool' object has no attribute 'nonzero'

任何线索,似乎y可能不是一个类似的实体。

我正在尝试按照示例文件中的代码来获取我自己的东西,如果这有点多余就会原谅。

我很感激帮助。

2 个答案:

答案 0 :(得分:0)

您正尝试将某些内容分配给可变的calles twos

twos = (y == 2).nonzero()[0]

Python告诉你(y == 2)没有这样的属性。这是逻辑,因为 括号会导致对y == 2True表达式False的评估。

在使用.的python中意味着您正在尝试访问某个实例的方法或属性。 如果你是一个字符串,它有方法限制它,所有字符串都有:

In [133]: A='lorem ipsum'
# pressed Tab
In [134]: A.
A.capitalize  A.endswith    A.isalnum     A.istitle     A.lstrip      A.rjust       A.splitlines  A.translate
A.center      A.expandtabs  A.isalpha     A.isupper     A.partition   A.rpartition  A.startswith  A.upper
A.count       A.find        A.isdigit     A.join        A.replace     A.rsplit      A.strip       A.zfill
A.decode      A.format      A.islower     A.ljust       A.rfind       A.rstrip      A.swapcase    
A.encode      A.index       A.isspace     A.lower       A.rindex      A.split       A.title       

如果你是python,numpy和matplotlib的新手,我建议你开始使用IPython。你对python的学习会更顺畅。

作为Tab按键的替代方法,您可以执行dir(someObject)

In [134]: dir(A)
Out[134]: 
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
  .... snipped...
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

答案 1 :(得分:0)

以下适用于我(来自iPython):

In [11]: y = arange(5); (y==2).nonzero()[0]
Out[11]: array([2])

而以下情况不是:

In [13]: y = range(5);  (y==2).nonzero()[0]
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
AttributeError: 'bool' object has no attribute 'nonzero'

所以@DSM的评论建议 - 确保y是一个numpy数组而不仅仅是一些列表或任何其他对象