【问题标题】:Bar plotting grouped Pandas条形图分组熊猫
【发布时间】:2017-03-23 09:06:27
【问题描述】:

我有一个关于绘制分组 DataFrame 数据的问题。

数据如下:

data =

index    taste    food

0        good     cheese
1        bad      tomato
2        worse    tomato
3        worse    cheese
4        good     meat
5        good     meat
6        bad      cheese
7        worse    tomato
8        worse    tomato
9        good     cheese
10       worse    meat
11       good     meat

我想要做的是制作一个条形图,将每个口味类别作为 x 轴(好、坏、差),并将每个口味类别中每种食物类型的百分比分布作为条形。

所以,看例如口味类别worse 我们有:3 tomato、1 cheese 和 1 meat。该类别中总共有 3+1+1=5 种食物类型,因此:

3/5=60% tomato, 1/5=20% cheese 和 1/5=20% meat

到目前为止,我已尝试将GroupByagg 与以下内容一起使用:

df_1 = data.groupby(['taste', 'food']).agg({'taste' : 'count'})
df_2 = df_1.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))

这似乎产生了我想要的结果:

              taste
taste food         
bad   cheese   50.0
      tomato   50.0
good  cheese   40.0
      meat     60.0
worse cheese   20.0
      meat     20.0
      tomato   60.0

但现在我被困在如何实际绘制这个问题上!

在 Excel 中,它看起来像:

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

我好像找到了一个例子:

making a stacked barchart in pandas

做足了:

df_3 = df_2.unstack()
df_3.plot(kind='bar',stacked=True, rot=1)

【讨论】:

    猜你喜欢
    • 2017-12-30
    • 2019-04-30
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2021-10-24
    • 2013-10-11
    • 2020-01-25
    相关资源
    最近更新 更多