Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python - Function to create grouped bar plot

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.

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')

enter image description here

question from:https://stackoverflow.com/questions/65875785/group-and-colour-a-pandas-bar-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

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()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...