0

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

1 Answer 1

1

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

fig,axes=plt.subplots(3,3,figsize=(15,12)) 
    for j, country in enumerate(df.Country.unique()):
        for i, 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)
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.