简体   繁体   English

条形图分组的熊猫

[英]Bar plotting grouped Pandas

I have a question regarding plotting grouped DataFrame data. 我有一个关于绘制分组DataFrame数据的问题。

The data looks like: 数据如下:

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

What I want to do is to have a bar plot having each taste category as x-axis (good, bad, worse) and the percentage distribution of each food-type within each taste category as bars. 我要做的是制作一个条形图,其中每个口味类别都作为x轴(好,坏,更糟),每个口味类别中每种食物类型的百分比分布为条形。

So, looking at eg taste category worse we have: 3 tomato , 1 cheese and 1 meat . 因此,从口味分类上看,我们worse :3 tomato ,1 cheese和1 meat In total there are 3+1+1=5 food-types in the category, and hence: 类别中总共有3 + 1 + 1 = 5种食物,因此:

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

So far I have tried to use GroupBy and agg with something like: 到目前为止,我已经尝试将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()))

which seems to yield my wanted result: 这似乎产生了我想要的结果:

              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

But now I am stuck on how to actually plot this! 但是现在我被困在如何实际绘制这个图上!

In Excel, it would look something like: 在Excel中,它看起来像:

在此处输入图片说明

I seem to have found an example: 我似乎找到了一个例子:

making a stacked barchart in pandas 在大熊猫中制作堆积的条形图

Sufficient doing: 做得足够:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM