2016-10-17 83 views
1

我想從我的數據框中創建一個堆積條形圖。我使用MultiIndex重命名行example。我只想繪製最後一列(Total Acc)。這是我到目前爲止有:如何在Pandas中使用行名進行堆積條形圖?

我的數據框: enter image description here

情節我得到:

enter image description here

情節我想要的:

enter image description here 這是我的代碼書面:

e=df['Total Acc'].round(4)*100 #Here I isolate the last column 
    e.plot.bar(stacked=True) 

編輯:

我改進了代碼。

e=df['Total Acc'].round(4)*100 
    row_awa = e.loc['AWA'] 
    row_rem = e.loc['REM'] 
    row_s1 = e.loc['S1'] 
    row_s2 = e.loc['S2'] 
    row_sws = e.loc['SWS'] 
    row_stades = e.loc['stades'] 

    row_awa.plot.bar(stacked=True) 
    row_rem.plot.bar(stacked=True) 
    row_s1.plot.bar(stacked=True) 
    row_s2.plot.bar(stacked=True) 
    row_sws.plot.bar(stacked=True) 
    row_stades.plot.bar(stacked=True) 

但它仍然無法正常工作!

enter image description here

回答

2

我很欣賞的人誰正在與色彩,一切的圖表的實際平局。使用以前的數據框你可以這樣做:

import pandas as pd 
import numpy as np 
df = pd.DataFrame(np.random.rand(24, 10)) 
df['Total Acc'] = df.sum(1) 
lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades'] 
lvl1 = ['10x20', '10x10', '10x5', '10x2', ] 
df.index = pd.MultiIndex.from_product([lvl0, lvl1]) 

現在你想要一個'堆疊'條形圖。撤消正在重置該索引你的工作,數據透視表,並繪製圖表:

df.reset_index().pivot('level_0', 'level_1', 'Total Acc').plot.bar(stacked=True) 

enter image description here

+0

謝謝。現在我已經學會了2個新的命令。 :) – Aizzaac