Issue
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.
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')
Solution
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()
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.