2017-03-14 39 views
1

我有以下數據框:如何繪製由兩列matplotlib分組一個數據幀和熊貓

     total_gross_profit 
    first_day_week var 
     Feb-06   1 45293.09 
        2 61949.54 
     Feb-13   1 44634.72 
        2 34584.15 
     Feb-20   1 43796.89 
        2 37308.57 
     Feb-27   1 44136.21 
        2 38237.67 
     Jan-16   1 74695.91 
        2 75702.02 
     Jan-23   1 86101.05 
        2 69518.39 
     Jan-30   1 65913.56 
        2 74823.94 
     Mar-06   1 34256.47 
        2 31953.00 

通過first_day_weekvar列編組,我需要做出一個柱狀圖,其中i在x軸有first_day_week和在不同顏色的first_day_week兩個條形地塊的每個條目爲每個值在var,類似的東西(以下爲數據barplot是完全以假):

enter image description here

回答

4

您需要通過unstack重塑然後DataFrame.plot.bar情節:

print (df.unstack()['total_gross_profit']) 
var     1   2 
first_day_week      
Feb-06   45293.09 61949.54 
Feb-13   44634.72 34584.15 
Feb-20   43796.89 37308.57 
Feb-27   44136.21 38237.67 
Jan-16   74695.91 75702.02 
Jan-23   86101.05 69518.39 
Jan-30   65913.56 74823.94 
Mar-06   34256.47 31953.00 


df.unstack()['total_gross_profit'].plot.bar(rot=0) 

graph

對於選別指標需要轉換爲datetime,排序,然後reindex

df1 = df.unstack()['total_gross_profit'] 
idx = pd.to_datetime(df1.index, format='%b-%d').sort_values().strftime('%b-%d') 
print (idx) 
['Jan-16' 'Jan-23' 'Jan-30' 'Feb-06' 'Feb-13' 'Feb-20' 'Feb-27' 'Mar-06'] 

df1.reindex(idx).plot.bar(rot=90) 

graph1

+0

完美,在繪製之前,有什麼方法可以在'first_day_week'中根據時間進行排序? – sanaz

+0

sort_index()會有幫助嗎? – sanaz

+0

對不起,給我一下 – jezrael