How can I optimize my code such that I am able to use a loop to plot histograms in subplots?

Viewed 40

This is what I have done so far. Basically, I would like to create 4 subplots to plot 4 individual histograms but I find that I am repeating the code over and over again. However, I do not know how to use a loop to optimize the code. I have also inserted an image at the bottom to show what I am trying to achieved.

This is the link of the dataset that I have used: https://data.gov.sg/dataset/weekly-number-of-dengue-and-dengue-haemorrhagic-fever-cases


import pandas as pd
import matplotlib.pyplot as plt

df_dengue_and_dhf_cases = pd.read_csv('weekly-number-of-dengue-and-dengue-haemorrhagic-fever-cases.csv',index_col=0)

df_dengue_and_dhf_2018 = df_dengue_and_dhf_cases.loc[2018].loc[:,"type_dengue":"number"]

df_dengue_and_dhf_2018 = df_dengue_and_dhf_2018.set_index("type_dengue") 

df_dengue_cases_2018 = df_dengue_and_dhf_2018.loc["Dengue"].dropna()

df_dengue_and_dhf_2017 = df_dengue_and_dhf_cases.loc[2017].loc[:,"type_dengue":"number"]

df_dengue_and_dhf_2017 = df_dengue_and_dhf_2017.set_index("type_dengue") 

df_dengue_cases_2017 = df_dengue_and_dhf_2017.loc["Dengue"].dropna()

df_dengue_and_dhf_2016 = df_dengue_and_dhf_cases.loc[2016].loc[:,"type_dengue":"number"]

df_dengue_and_dhf_2016 = df_dengue_and_dhf_2016.set_index("type_dengue") 

df_dengue_cases_2016 = df_dengue_and_dhf_2016.loc["Dengue"].dropna()

df_dengue_and_dhf_2015 = df_dengue_and_dhf_cases.loc[2015].loc[:,"type_dengue":"number"]

df_dengue_and_dhf_2015 = df_dengue_and_dhf_2015.set_index("type_dengue") 

df_dengue_cases_2015 = df_dengue_and_dhf_2015.loc["Dengue"].dropna()

fig,ax = plt.subplots(2,2,figsize=(16,8),sharey=True)

ax[0,0].hist(df_dengue_cases_2018.T,label="Dengue Cases in 2018",histtype="bar",color="crimson")

ax[0,1].hist(df_dengue_cases_2017.T,label="Dengue Cases in 2017",histtype="bar",color="darkblue")

ax[1,0].hist(df_dengue_cases_2016.T,label="Dengue Cases in 2016",histtype="bar",color="rebeccapurple")

ax[1,1].hist(df_dengue_cases_2015.T,label="Dengue Cases in 2015",histtype="bar",color="darkgreen")

ax[0,0].set_xlabel("Number of Dengue Cases",fontsize=13,fontweight="bold")

ax[0,0].set_ylabel("Number of Weeks",fontsize=13,fontweight="bold")

ax[0,0].set_title("Distribution of the Weekly Number of Dengue Cases in 2018",fontsize=14,fontweight="bold")

ax[0,1].set_xlabel("Number of Dengue Cases",fontsize=13,fontweight="bold")

ax[0,1].set_title("Distribution of the Weekly Number of Dengue Cases in 2017",fontsize=14,fontweight="bold")

ax[1,0].set_xlabel("Number of Dengue Cases",fontsize=13,fontweight="bold")

ax[1,0].set_ylabel("Number of Weeks",fontsize=13,fontweight="bold")

ax[1,0].set_title("Distribution of the Weekly Number of Dengue Cases in 2016",fontsize=14,fontweight="bold")

ax[1,1].set_xlabel("Number of Dengue Cases",fontsize=13,fontweight="bold")

ax[1,1].set_title("Distribution of the Weekly Number of Dengue Cases in 2015",fontsize=14,fontweight="bold")

ax[0,0].legend()
ax[0,1].legend()
ax[1,0].legend()
ax[1,1].legend()

fig.tight_layout()

plt.show()

Histogram Image

1 Answers

I guess you are supposed to do a histogram on a subset of the data, so it makes sense to subset the data first:

import pandas as pd
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

years_ = [2018,2017,2016,2015]

df = pd.read_csv('./weekly-number-of-dengue-and-dengue-haemorrhagic-fever-cases.csv')
df = df[(df.type_dengue=="Dengue") & (df.year.isin(years_))].dropna()

Then we define the palette, in the same order as years_ from above:

pal = ["crimson","darkblue","rebeccapurple","darkgreen"]

We can use seaborn:

g = sns.FacetGrid(df, col="year",sharex=False,col_wrap=2,
                  palette=pal,hue="year",
                  col_order=years_,
                 height=3,aspect=2)
g.map(plt.hist,"number")

enter image description here

We can also do it in matplotlib:

fig,ax = plt.subplots(2,2,figsize=(16,8),sharey=True)
ax = ax.flatten()
for i in range(len(years_)):
    ax[i].hist(df[df.year==years_[i]].number,
               label="Dengue Cases in "+str(years_[i]),histtype="bar",color=pal[i])
    ax[i].set_xlabel("Number of Dengue Cases",fontsize=13,fontweight="bold")
    ax[i].set_ylabel("Number of Weeks",fontsize=13,fontweight="bold")
    ax[i].set_title("Distribution of the Weekly Number of Dengue Cases in "+str(years_[i]),
                    fontsize=14,fontweight="bold")
    ax[i].legend()

fig.tight_layout()
plt.show()

enter image description here

Related