2017-10-08 44 views
0

下面的代碼是讓誰得到拒絕,並在特定學年招收女生總數:的Python 3.0熊貓和Matplotlib:巴()等matplotlib地塊不接受字符串數據幀指數爲x軸

query1=All_Females_count[['Admit','Freq']].groupby('Admit').sum() 
print(query1) 
query1.set_index(data.Admit.unique()) 
query1.plot(kind='bar') 

上面的代碼似乎工作沒關係,給我柱狀圖預期。但是,下面的代碼不會:

Admit Gender Dept Freq 
2 Admitted Female A 89 
3 Rejected Female A 19 
6 Admitted Female B 17 
7 Rejected Female B 8 
10 Admitted Female C 202 
11 Rejected Female C 391 
14 Admitted Female D 131 
15 Rejected Female D 244 
18 Admitted Female E 94 
19 Rejected Female E 299 
22 Admitted Female F 24 
23 Rejected Female F 317 

誰能告訴我爲什麼:作爲如下

plt.bar(query1.index,query1.Freq) 
plt.show() 

All_Females_count數據幀?唯一的解決方法是使用帶有數字數據的標籤嗎?

我還發現此討論主題:https://github.com/matplotlib/matplotlib/issues/2516/ 對同一主題。

這是一個非常類似的問題。但是,它沒有解決我的問題:Using a Pandas dataframe index as values for x-axis in matplotlib plot

回答

0

matplotlib通常需要其x軸的數值。作爲the documentation for plt.bar()國家(重點煤礦):

×:標量

酒吧的x座標序列。

一個相當簡單的方式重現pandas的行爲是從0索引調用bar()用列表值的個數,然後用該指數的實際內容替換蜱標籤。

plt.bar(range(len(query1.index)),query1.Freq) 
plt.xticks(range(len(query1.index)), query1.index) 
plt.show() 
+0

太謝謝你了!它的作品像一個魅力:) –

+0

很高興聽到。如果你覺得你的問題已經解決,考慮接受使用綠色刻度線關閉該線程 –

+0

我絕對會得到答案的一個,但我是很新的計算器:( –

0

要在條形圖上獲取標籤,您需要將數值提供給第一個參數。標籤可以使用tick_labels參數進行設置。

import matplotlib.pyplot as plt 

x = list("ABC") 
y = [1,3,4] 

plt.bar(range(len(y)), y, tick_label=x) 

plt.show()