pandas 创建分组条形图的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47796264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function to create grouped bar plot
提问by Rilcon42
The goal here is to create a grouped bar plot, not subplots like the image below
这里的目标是创建一个分组的条形图,而不是像下图这样的子图
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.
有没有一种简单的方法可以在 Python 中创建分组条形图?现在我得到单独的条形图,而不是一个图上的单独条形图。
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'])
%matplotlib inline
df.groupby(['group']).plot(kind='bar')
回答by ImportanceOfBeingErnest
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
Pandas 将按列显示分组条。每行但不同列中的条目将在结果图中构成一个组。因此,您需要“重塑”数据框以将“组”作为列。在这种情况下,您可以像
df.pivot("column", "group", "val")
producing
生产
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()