Search code examples
pythonfor-loopmatplotlibseabornsubplot

How to write a For loop for 2*3 subplots


I have written this long piece of code to make a subplot like below subplot

My code is like this:

fig, axes = plt.subplots(2, 3, figsize=(15, 8), sharey=True)
fig.tight_layout(h_pad=4)
Asia_data=df[df.Region=='Asia']
Africa_data=df[df.Region=='Africa']
Europe_data=df[df.Region=='Europe']
ME_data=df[df.Region=='Middle East']
Oceania_data=df[df.Region=='Oceania']
America_data=df[df.Region=='The Americas']

sns.histplot(ax=axes[0,0], data=Africa_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
sns.histplot(ax=axes[0,1], data=Asia_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
sns.histplot(ax=axes[0,2], data=Europe_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
sns.histplot(ax=axes[1,0], data=ME_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
sns.histplot(ax=axes[1,1], data=Oceania_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
sns.histplot(ax=axes[1,2], data=America_data,x="Life Expectancy Female", 
kde=True,stat='probability').set(xlabel=None)
axes[0,0].set_title('Africa')
axes[0,1].set_title('Asia')
axes[0,2].set_title('Europe')
axes[1,0].set_title('Middle East')
axes[1,1].set_title('Oceania')
axes[1,2].set_title('The Americas')
fig.suptitle('Histogram and KDE of Life Exppectancy of Wemon', fontsize=15)
plt.subplots_adjust(top=0.9)

How could I improve this code and put all these steps into a For loop? Thank you for your time


Solution

  • Use zip:

    regions = ['Asia', 'Africa', 'Europe', 
               'Middle East', 'Oceania', 'The Americas']
    
    for ax, region in zip(axes.flat, regions):
        sns.histplot(ax=ax, data=df[df.Region == region],
                     x="Life Expectancy Female", kde=True, 
                     stat='probability').set(xlabel=None)
        ax.set_title(region)
    

    Or consider using FacetGrid.