pandas pivot table to stacked条形图

时间:2018-02-15 03:52:37

标签: python pandas matplotlib

我正在尝试使用此数据透视表,并根据战斗类型创建一个有关输赢的叠加条形图。

import pandas as pd
import numpy as np

np.random.seed(1)
df = pd.DataFrame({'attacker_outcome':np.random.choice(['win', 'loss'], 20, replace=True),
                'battle_type':np.random.choice(['pitched battle', 'siege', 'ambush', 'razing'], 20, replace=True)})


   attacker_outcome     battle_type
0              loss          ambush
1              loss           siege
2               win          ambush
3              loss           siege
4              loss           siege
5               win          ambush
6               win           siege
7               win          razing
8              loss           siege
9              loss          ambush
10             loss          razing
11             loss           siege
12              win          razing
13             loss          razing
14              win          ambush
15              win  pitched battle
16             loss          ambush
17             loss           siege
18              win  pitched battle
19             loss           siege

我尝试初始化新列groupbycount。我正试图从这个数据透视表创建一个堆积条形图,并开始迷失在这里。我明白了:

df.assign(count =1 ).groupby(['attacker_outcome', 'battle_type']).count().plot.bar(stacked=True)

barchart

感谢任何帮助!

2 个答案:

答案 0 :(得分:7)

您可以通过分组和取消堆栈来完成此任务:

df.groupby('battle_type')['attacker_outcome']\
    .value_counts()\
    .unstack(level=1)\
    .plot.bar(stacked=True)

enter image description here

答案 1 :(得分:1)

这里的代码更加严格:

df.pivot_table(index='battle_type', columns='attacker_outcome', aggfunc='size').plot.barh(stacked=True)

通过Minimally Sufficient Pandas

结果为

enter image description here