Issue
I have a simple long-form dataset I would like to generate bar charts from. The dataframe looks like this:
data = {'Year':[2019,2019,2019,2020,2020,2020,2021,2021,2021],
'Month_diff':[0,1,2,0,1,2,0,1,2],
'data': [12,10,13,16,12,18,19,45,34]}
df = pd.DataFrame(data)
I would like to plot a bar chart that has 3 rows, each for 2019, 2020 and 2021. X axis being month_diff
and data
goes on Y axis.
How do I do this?
If the data was in different columns, then I could have just used this code:
df.plot(x="X", y=["A", "B", "C"], kind="bar")
But my data
is in a single column and ideally, I'd like to have different row for each year.
Solution
seaborn.catplot
The simplest way is using the seaborn.catplot
wrapper, as Johan said:
import seaborn as sns
sns.catplot(kind='bar', height=2, aspect=4,
data=df, x='Month_diff', y='data', row='Year')
DataFrame.groupby
Without seaborn, you can iterate df.groupby('Year')
:
fig, axs = plt.subplots(3, 1, sharex=True, sharey=True)
for (name, data), ax in zip(df.groupby('Year'), axs):
data.plot.bar(ax=ax, x='Month_diff', y='data', legend=False, rot=0)
ax.set_title(name)
pivot
+ DataFrame.plot
Note that if you prefer a single grouped bar chart (which you alluded to at the end), you can pivot
into DataFrame.plot
:
df.pivot(index='Month_diff', columns='Year', values='data').plot.bar()
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.