pandas 数据透视表到堆积的条形图 [英] pandas pivot table to stacked bar chart

查看:240
本文介绍了 pandas 数据透视表到堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此数据透视表,并创建按战斗类型划分的获胜和失败的堆积条形图.

I'm trying to take this pivot table and create a stacked bar chart of wins and losses by battle type.

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.我正在尝试从此数据透视表创建一个堆积的条形图,并开始在这里迷路.我得到这个:

I tried to initialize a new column, groupby and count. I'm trying to create a stacked bar chart from this pivot table, and starting to get lost here. I'm getting this:

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

感谢您的帮助!

推荐答案

您可以通过分组和堆叠来完成此操作:

You can accomplish this through grouping and unstacking:

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

这篇关于 pandas 数据透视表到堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆