Home > Software design >  plot data using nested loop in matplotlib
plot data using nested loop in matplotlib

Time:07-13

I am trying to create line chart for each data created by nested loop. This is the first five rows of the main dataframe: enter image description here There are three unique countries in "Country" column. I want for each country to plot "hum","pre" and "temp" data separately. So there should be 9 charts (3x3).

This is my code:

fig,axes=plt.subplots(3,3,figsize=(15,15))
for country in df.Country.unique():
    for i in ["pre","hum","temp"]:
        for ax in axes.ravel():
            grouped=df[(df.Country==country)&(df.year==2016)].groupby("date")[i].mean().reset_index().sort_values("date")
            grouped.plot(ax=ax,kind="line",x="date",y=i,xlabel="")
            ax.set_title(i " for " country,size=10)
plt.show()

I get nine charts but all like this: enter image description here

CodePudding user response:

You need to plot on a single axis for each combination of country and variable.

for jj, country in enumerate(df.Country.unique()):
    for ii, var in enumerate(["pre","hum","temp"]):
        ax = axes[i, j]
        grouped=df[(df.Country==country)&(df.year==2016)].groupby("date")[var].mean().reset_index().sort_values("date")
        grouped.plot(ax=ax,kind="line",x="date",y=var,xlabel="")
        ax.set_title(var " for " country,size=10)
  • Related