Search code examples
pythonmatplotlibseabornboxplotsubplot

Subplot for seaborn boxplot


I have a dataframe like this

import seaborn as sns
import pandas as pd
%pylab inline

df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'], 
                   'b': [1,2,1,2,1,2,1,2,1,1], 
                   'c': [1,2,3,4,6,1,2,3,4,6]})

A single boxplot is OK:

sns.boxplot(y="b", x="a", data=df, orient='v')

But I want to build a subplot for all variables. I tried:

names = ['b', 'c']
plt.subplots(1,2)
sub = []

for name in names:
    ax = sns.boxplot(  y=name, x= "a", data=df,  orient='v' )
    sub.append(ax)

but it outputs:

enter image description here


Solution

  • 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