Cybertron
Cybertron

Reputation: 155

subplot by group in python pandas

I wanna make subplots for the following data. I averaged and grouped together. I wanna make subpolts by country for x-axis resource and y-axis average.

country       resource     average
india         water         76
india         soil          45
india         tree          60
US            water         45
US            soil          70
US            tree          85
Germany       water         76
Germany       soil          65
Germany       water         56

Grouped = df.groupby(['country','resource'])['TTR in minutes'].agg({'average': 'mean'}).reset_index()

I tried but couldn't plot in subplots

Upvotes: 2

Views: 3620

Answers (1)

piRSquared
piRSquared

Reputation: 294228

g = df.groupby('country')

fig, axes = plt.subplots(g.ngroups, sharex=True, figsize=(8, 6))

for i, (country, d) in enumerate(g):
    ax = d.plot.bar(x='resource', y='average', ax=axes[i], title=country)
    ax.legend().remove()

fig.tight_layout()

enter image description here

Upvotes: 3

Related Questions