熊猫从条形图变为堆积条形图

时间:2019-11-07 03:24:19

标签: python pandas dataframe stacked

我试图在当月之前在上方绘制这些数据。但我想将它们堆叠在色相部分上

这是数据:

    Activity Month  hue     Activity Hours
0   Apr-19          110     212.00
1   Apr-19          120     1060.00
2   Apr-19          Other   35381.25
3   May-19          110     2494.00
4   May-19          120     824.00
5   May-19          Other   31722.50
6   Jun-19          110     1792.00
7   Jun-19          120     1521.00
8   Jun-19          Other   27708.50
9   Jul-19          110     688.00
10  Jul-19          120     476.00
11  Jul-19          Other   34283.50
12  Aug-19          110     270.00
13  Aug-19          120     352.00
14  Aug-19          Other   21359.90

这是我现在绘制它们的代码。

import pandas as pd

data = [['Apr-19', '110', 212], ['Apr-19', '120', 1060.00],
        ['Apr-19', 'Others', 35381.25], ['May-19', '110', 2494.00],
        ['May-19', '120', 824.00], ['May-19', 'Others', 31722.50],
        ['Jun-19', '110', 1792.00], ['Jun-19', '120', 1521.00], 
        ['Jun-19', 'Others', 27708.50], ['Jul-19', '110', 688.00], 
        ['Jul-19', '120', 476.00], ['Jul-19', 'Others', 34283.50]]
df1 = pd.DataFrame(data, columns = ['Activity Month', 'hue', 'Activity Hours'])

df2 = df1.groupby(['Activity Month'])['Activity Hours'].sum()

plt.ylabel('Activity Hours')
plt.xlabel('Month')
sns.barplot(x='Activity Month', y='Activity Hours', hue='hue', data=df1)

enter image description here

我想像下面的插图一样堆叠它们:

enter image description here

1 个答案:

答案 0 :(得分:1)

df1 = pd.DataFrame(data, columns = ['Activity Month', 'hue', 'Activity Hours'])
df2 = df1.groupby(['Activity Month',"hue"])['Activity Hours'].sum().unstack("hue")

ax = df2.plot(kind='bar', stacked=True)
plt.show()

结果:

enter image description here