【发布时间】: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
到目前为止,我已尝试将GroupBy 和agg 与以下内容一起使用:
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 中,它看起来像:
【问题讨论】:
-
这个例子对你有帮助吗? seaborn.pydata.org/examples/factorplot_bars.html
-
感谢@Zealseeker。我去看看。经典,一个人在处理并在此处输入问题时找到了您自己问题的答案:)