简体   繁体   English

如何从按间隔分为两列的数据框创建分组条形图

[英]How to create grouped barplot from dataframe grouped by two columns with intervals

I grouped the data by two columns ( 'a' and 'b' ). 我将数据分为两列( 'a''b' )。 And for each column, I cut it into bins. 对于每一列,我将其切成垃圾箱。 For each crossed bin, I would like to have the sum of 'c' . 对于每个交叉的垃圾箱,我希望得到'c'的总和。 Then I want to create a grouped plot for the sum of 'c' . 然后,我想为'c'的总和创建一个分组图。 However, when I use .plot(kind='bar') after the grouped data, the bars were not grouped together. 但是,当我在分组数据之后使用.plot(kind='bar') ,这些条未分组在一起。

grouped = df.groupby([pd.cut(df['a'], [0, 1, 2, 3]), pd.cut(df['b'], [0, 101, 300, 500])])
grouped = grouped.c.sum()
grouped.plot(kind='bar')

ungrouped barplot 未分组的barplot

I would like the graph to be grouped by 'a' with different color standing for 'b' . 我希望图形按'a'分组,用不同的颜色代表'b' I have tried .unstack().plot(kind='bar') ; 我已经尝试过.unstack().plot(kind='bar') ; however, it returns an error: 但是,它返回一个错误:

cannot determine next label for type 无法确定类型的下一个标签

Given the following example data 给定以下示例数据

df = pd.DataFrame({'a': [8, 49, 81, 52, 22, 24, 32, 67, 24, 21, 78, 16, 86, 19, 4, 88, 4, 20, 20, 1],
                   'b': [2, 49, 49, 70, 31, 47, 98, 26, 55, 36, 17, 39, 56, 80, 52, 36, 42, 69, 73, 70],
                   'c': [22, 99, 31, 95, 16, 32, 81, 20, 58, 23, 53, 5, 0, 81, 8, 68, 16, 36, 35, 54]})

and your setup 和你的设置

grouped = df.groupby([pd.cut(df['a'], [16, 30, 67, 86]),
                      pd.cut(df['b'], [0, 26, 49, 100])])
grouped = grouped['c'].sum()

you have two options 你有两个选择

  •  (grouped.reset_index() .pivot('a', 'b') .plot(kind='bar')); 

    在此处输入图片说明

  •  grouped = grouped.unstack() grouped.columns = grouped.columns.categories grouped.plot(kind='bar'); 

    在此处输入图片说明

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

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