2012-10-25 22 views
0

我想繪製一些數據,並從指出的行中得到此錯誤。我搜索了該行,但在這個問題上找不到任何有意義的討論。我對Python很陌生,所以試圖在我走的時候找出這些東西。python matplotlib錯誤,同時繪製一些數據

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可能不是一個可比的實體。

我想按摩示例文件中的代碼來讓我自己的東西去原諒,如果這有點多餘。

我的確很感謝幫助。

回答

0

您正在嘗試的東西分配給varaible卡列斯twos

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

一個Python的告訴你(y == 2)有沒有這樣的屬性。這是邏輯,因爲 括號會導致表達式y == 2的評估,其可以是TrueFalse

在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的學習會更順暢。

作爲替代選項卡按你可以做dir(someObject)

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

只是爲了澄清,而這裏'y == 2'返回一個布爾值,它不必返回True或False。如果'y'是一個numpy數組(它大概是在原始代碼中),那麼它會返回一個bools數組,並且*會*有一個非零的方法。 – DSM

+0

@DSM,好點。在這種情況下,可以使用'try'和'except'或者在檢查'y'是一個numpy數組之前。感謝您指出了這一點。 – Oz123

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數組,而不僅僅是一些列表或任何其他對象

相關問題