merchmallow
merchmallow

Reputation: 794

Iterating over a DF to make plots

I have da DF with 4 columns:

    Date      |  Year  | Month | Production
  2010-01-01     2010      1        10
  2010-02-01     2010      2        20
                 2010     ...       30
                 2010      12       33
                 2011      1        44
                 2020     ...      ....

column [Date] is the index. I am ploting a graph this way:

plt.plot(df.index, df['Production'])

I get a plot from years 2010 to 2020. Working just fine.

What i want to do is to plot a graph by year, monthly like this:

for year 2010:  plot months X Production
for year 2011:  plot months X Production

How can i iterate over my DF to plot all this graphs in 3 graphs per row, for example?

I tried:

years = df['Year'].unique()
for year in years:
    plt.plot(years[i], df['Production'])

but dosent work!

I want a plot like the image below: enter image description here

Upvotes: 0

Views: 36

Answers (1)

Corralien
Corralien

Reputation: 120409

The code below should do the job:

nplt = df['Year'].nunique()
ncols = 3
nrows = nplt // ncols + (1 if nplt % ncols else 0)

# Create figure and subplots
fig, axs = plt.subplots(nrows, ncols, sharey=True, sharex=True, figsize=(15, 15))
fig.suptitle('Production')

# Plot one year per subplot
for ax, (year, dfy) in zip(axs.flat, df.groupby('Year')):
    ax.set_title(year)
    ax.plot(dfy['Month'], dfy['Production'])

# Remove unused subplots
for ax in axs.flat[nplt:]:
    fig.delaxes(ax)

Production plot - 3 columns

You can use seaborn for a better rendering.

Upvotes: 1

Related Questions