2015-11-24 79 views
4

我有以下數據框df熊貓:如何繪製帶有標籤的數據框的barchar?

   timestamp  objectId result 
0 2015-11-24 09:00:00  Stress  3 
1 2015-11-24 09:00:00 Productivity  0 
2 2015-11-24 09:00:00  Abilities  4 
3 2015-11-24 09:00:00  Challenge  0 
4 2015-11-24 10:00:00 Productivity  87 
5 2015-11-24 10:00:00  Abilities  84 
6 2015-11-24 10:00:00  Challenge  58 
7 2015-11-24 10:00:00  Stress  25 
8 2015-11-24 11:00:00 Productivity  93 
9 2015-11-24 11:00:00  Abilities  93 
10 2015-11-24 11:00:00  Challenge  93 
11 2015-11-24 11:00:00  Stress  19 
12 2015-11-24 12:00:00  Challenge  90 
13 2015-11-24 12:00:00  Abilities  96 
14 2015-11-24 12:00:00  Stress  94 
15 2015-11-24 12:00:00 Productivity  88 
16 2015-11-24 13:00:00 Productivity  12 
17 2015-11-24 13:00:00  Challenge  17 
18 2015-11-24 13:00:00  Abilities  89 
19 2015-11-24 13:00:00  Stress  13 

我想實現像下面Picture taken from here http://pandas.pydata.org/pandas-docs/stable/visualization.html 一個條形圖凡a,b,c,d不是會有列ObjectID y軸應該對應於該列的標籤result,x軸應該是timestamp列的值。

我嘗試了幾件事,但沒有奏效。這是最接近的,但plot()方法不通過參數進行任何定製(例如,kind='bar'不起作用)。

groups = df.groupby('objectId') 
sgb = groups['result'] 
sgb.plot() 

還有其他想法嗎?

+0

您可以指定你想繪製*完全* *?因爲您顯示的數字似乎與您顯示的數據無關。應該用不同的顏色,通過哪些變量應該分組? – joris

+0

你好joris,謝謝你的回答。我編輯了我的問題。我希望這個問題現在已經很清楚了 – dimstudio

回答

1

@NaderHisham的答案是非常簡單的解決方案!
但只是作爲一個參考,如果您由於某種原因不能使用seaborn,這是一個純粹的大熊貓/ matplotlib解決方案:

你需要重塑你的數據,因此不同的ObjectID成爲列:

In [20]: df.set_index(['timestamp', 'objectId'])['result'].unstack() 
Out[20]: 
objectId Abilities Challenge Productivity Stress 
timestamp 
09:00:00   4   0    0  3 
10:00:00   84   58   87  25 
11:00:00   93   93   93  19 
12:00:00   96   90   88  94 
13:00:00   89   17   12  13 

如果你做的這個柱狀圖,你得到期望的結果:

In [24]: df.set_index(['timestamp', 'objectId'])['result'].unstack().plot(kind='bar') 
Out[24]: <matplotlib.axes._subplots.AxesSubplot at 0xc44a5c0> 

enter image description here

+0

非常感謝你,我的回答完全回答。 – dimstudio

3
import seaborn as sns 

In [36]: 
df.timestamp = df.timestamp.factorize()[0] 

In [39]: 
df.objectId = df.objectId.map({'Stress' : 'a' , 'Productivity' : 'b' , 'Abilities' : 'c' , 'Challenge' : 'd'}) 

In [41]: 
df 
Out[41]: 
    timestamp objectId result 
0  0   a   3 
1  0   b   0 
2  0   c   4 
3  0   d   0 
4  1   b   87 
5  1   c   84 
6  1   d   58 
7  1   a   25 
8  2   b   93 
9  2   c   93 
10  2   d   93 
11  2   a   19 
12  3   d   90 
13  3   c   96 
14  3   a   94 
15  3   b   88 
16  4   b   12 
17  4   d   17 
18  4   c   89 
19  4   a   13 

In [40]: 
sns.barplot(x = 'timestamp' , y = 'result' , hue = 'objectId' , data = df); 

enter image description here

+0

你的回答非常好。謝謝,但joris給出的解決方案也是非常有效的。 – dimstudio

相關問題