2017-03-04 66 views
-3

我正在研究癌症細胞,我試圖做一個餅圖來顯示有絲分裂X的死亡百分比。因此,我有一個數組命名mitosis_events和另一個名爲Death_events以下是我的代碼:python在創建餅圖和數組時出錯

import matplotlib.pyplot as plt 

mitotic_events[get_generation_number(cell)] += 1 
death_events[len(cell)-1] += 1 

#Simple Pie chart 

# The slices will be ordered and plotted counter-clockwise. 
labels = 'Mitosis', 'Deaths' 
sizes = [mitotic_events, death_events] 
colors = ['Green', 'Red' ] 
explode = (0, 0.1) # only "explode" the 2nd slice (i.e. 'Hogs') 

plt.pie(sizes, explode=explode, labels=labels, colors=colors, 
    autopct='%1.1f%%', shadow=True, startangle=90) 
# Set aspect ratio to be equal so that pie is drawn as a circle. 
plt.axis('equal') 

plt.show() 

,我在控制檯收到此錯誤:

TypeError: only length-1 arrays can be converted to Python scalars 

我不知道該如何解決?我知道這個問題是在這一行:

sizes = [mitotic_events, death_events] 

謝謝你在先進

+1

嘗試用打印至少調試您的代碼。此外,你可以谷歌你的錯誤,並找到答案。 –

+0

我明顯使用了搜索引擎,但沒有涉及我的請求+我知道錯誤出現在這一行「」sizes = [mitotic_events,death_events]「」 –

+0

您的代碼片段並不完整,因爲您沒有顯示mitotic_events的定義, 'death_events'和'plt'(儘管最後一個很明顯)。請參見[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

回答

0

您的代碼不會完全展現的mitotic_eventsdeath_events的定義,因爲這些使用get_generation_number()cell這是不是在你的代碼中定義片段。你也不會顯示如何前兩個變量是創建 - 你只是顯示他們如何更新。然而,我們從報表

mitotic_events[get_generation_number(cell)] += 1 
death_events[len(cell)-1] += 1 

兩個mitotic_eventsdeath_events是名單見。您然後定義

sizes = [mitotic_events, death_events] 

因此sizes是列表的列表。然後嘗試將sizes作爲第一個參數傳遞給pyplot的pie()函數。

但是,pie()的第一個參數必須是數組或數字列表的第一個參數。 documentation意味着但沒有說清楚,但examplestutorial表明必須如此。當pyplot讀取sizes時,它會查看sizes列表中的第一項,並且它看起來不是數字(標量),而是一個列表。 Pyplot顯然試圖將內部列表mitotic_events更改爲標量,但它是長度大於1的列表,因此轉換失敗。 Pyplot然後給你那不是非常有用的錯誤信息。

解決方案是爲您構建sizes,因此它是一個數字列表。也許你應該

sizes = mitotic_events + death_events 

構建它適當地組合這兩個名單,但你可能需要改變你的其他參數pie()。你沒有提供足夠的信息讓我說更多。