如何创建分组条形图 [英] How to create a grouped bar plot

查看:46
本文介绍了如何创建分组条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的目标是创建一个分组的条形图,而不是像下图那样的子图

有没有一种简单的方法可以在 Python 中创建分组条形图?现在我得到了单独的条形图,而不是一个图中的单独条形图.

Is there a simple way to create a grouped bar plot in Python? Right now I get separate bar plots, instead of separate bars on one plot.

import pandas as pd

df = pd.DataFrame([['g1', 'c1', 10], ['g1', 'c2', 12], ['g1', 'c3', 13], ['g2', 'c1', 8], ['g2', 'c2', 10], ['g2', 'c3', 12]], columns=['group', 'column', 'val'])

  group column  val
0    g1     c1   10
1    g1     c2   12
2    g1     c3   13
3    g2     c1    8
4    g2     c2   10
5    g2     c3   12
    

df.groupby(['group']).plot(kind='bar')

推荐答案

Pandas 将按列显示分组条.每行但不同列中的条目将在结果图中构成一个组.因此,您需要重塑"数据框以将组"作为列.在这种情况下,您可以像

Pandas will show grouped bars by columns. Entries in each row but different columns will constitute a group in the resulting plot. Hence you need to "reshape" your dataframe to have the "group" as columns. In this case you can pivot like

df.pivot("column", "group", "val")

制作

group   g1  g2
column        
c1      10   8
c2      12  10
c3      13  12

绘制此图将生成分组条形图.

Plotting this will result in a grouped bar chart.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([['g1','c1',10],['g1','c2',12],['g1','c3',13],['g2','c1',8],
                   ['g2','c2',10],['g2','c3',12]],columns=['group','column','val'])

df.pivot("column", "group", "val").plot(kind='bar')

plt.show()

这篇关于如何创建分组条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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