2017-08-29 38 views
3

這是我的數據框df如何用非數字X軸創建條形圖?

bin    qty 
0 (0.0, 25.0]  3634.805042 
1 (25.0, 50.0] 1389.567460 
2 (50.0, 75.0] 1177.400000 
3 (75.0, 100.0] 898.750000 
4 (100.0, 125.0] 763.000000 

我想創建一個柱狀圖就像一個直方圖。 Y軸應該是qty和X軸應該是bin,例如 「(0.0,25.0]」,垂直旋轉

我想這一點,但它失敗,因爲bin不是數字:

plt.bar(df.bin, df.qty, align='center', alpha=0.5) 
plt.show() 

回答

2

讓我們嘗試使用熊貓劇情:

df.plot.bar('bin','qty', alpha=.5) 

輸出:

enter image description here

使用matplotlib:

x = pd.np.arange(len(df['bin'])) 
fig,ax = plt.subplots(figsize=(14,8)) 
ax.bar(x,df['qty']) 
width = .35 
ax.set_xticks(x + width // 2) 
ax.set_xticklabels(df['bin']) 
plt.show() 

輸出:

enter image description here

+0

如何配置它,例如,應用於像'圖,AX = plt.subplots(figsize =(14,8))',着色等?所以我更喜歡matplotlib。 – Dinosaurius

+0

@Dinosaurius看到這個[示例](https://matplotlib.org/examples/api/barchart_demo.html) –

0

如果你正在嘗試使用matplotlib,你的bin列不是一個有效的對象。 matplotlib.pyplot.bar需要一系列與每個bin的左值相等的標量。所以,你的數據框應該像

 bin    qty 
    0 0.0  3634.805042 
    1 25.0 1389.567460 
    2 50.0 1177.400000 
    3 75.0  898.750000 
    4 100.0 763.000000