Subplot for seaborn boxplot Subplot for seaborn boxplot python-3.x python-3.x

Subplot for seaborn boxplot


We create the figure with the subplots:

f, axes = plt.subplots(1, 2)

Where axes is an array with each subplot.

Then we tell each plot in which subplot we want them with the argument ax.

sns.boxplot(  y="b", x= "a", data=df,  orient='v' , ax=axes[0])sns.boxplot(  y="c", x= "a", data=df,  orient='v' , ax=axes[1])

And the result is:

enter image description here


names = ['b', 'c']fig, axes = plt.subplots(1,2)for i,t in enumerate(names):    sns.boxplot(y=t, x="a", data=df, orient='v', ax=axes[i % 2])

Example:

names = ['b', 'c']fig, axes = plt.subplots(1,2)sns.set_style("darkgrid")flatui = ["#95a5a6", "#34495e"]for i,t in enumerate(names):    sns.boxplot(y=t, x= "a", data=df, orient='v', ax=axes[i % 2], palette=flatui)

enter image description here


If you wish to iterate through multiple different subplots, use plt.subplots:

import matplotlib.pyplot as plt# Creating subplot axesfig, axes = plt.subplots(nrows,ncols)# Iterating through axes and namesfor name, ax in zip(names, axes.flatten()):    sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)

Working example:

import numpy as np# example datadf = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'],                    'b': np.random.randint(1,8,10),                    'c': np.random.randint(1,8,10),                   'd': np.random.randint(1,8,10),                   'e': np.random.randint(1,8,10)})names = df.columns.drop('a')ncols = len(names)fig, axes = plt.subplots(1,ncols)for name, ax in zip(names, axes.flatten()):    sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)    plt.tight_layout()

enter image description here