Search code examples
pythonmatplotlibseabornsubplot

Plotting two seaborn graphs in subplots


I need to plot two graphs side by side. Here the column in my dataset which I am interested in.

X
1
53
12
513
135
125
21
54
1231

I did

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mean = df['X'].mean()
    
fig, ax =plt.subplots(1,2)
sns.displot(df, x="X", kind="kde", ax=ax[0]) # 1st plot
plt.axvline(mean, color='r', linestyle='--') # this add just a line on the previous plot, corresponding to the mean of X data
sns.boxplot(y="X", data=df, ax=ax[2]) # 2nd plot

but I have this error: IndexError: index 2 is out of bounds for axis 0 with size 2, so the use of subplots is wrong.


Solution

  • sns.boxplot(..., ax=ax[2]) should use ax=ax[1] as there doesn't exist an ax[2].

    sns.displot is a figure-level function, which creates its own figure, and doesn't accept an ax= parameter. If only one subplot is needed, it can be replaced by sns.histplot or sns.kdeplot.

    plt.axvline() draws on the "current" ax. You can use ax[0].axvline() to draw on a specific subplot. See What is the difference between drawing plots using plot, axes or figure in matplotlib?

    The following code has been tested with Seaborn 0.11.1:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    sns.set()
    df = pd.DataFrame({'X': [1, 53, 12, 513, 135, 125, 21, 54, 1231]})
    mean = df['X'].mean()
    
    fig, ax = plt.subplots(1, 2)
    sns.kdeplot(data=df, x="X", ax=ax[0])
    ax[0].axvline(mean, color='r', linestyle='--')
    sns.boxplot(y="X", data=df, ax=ax[1])
    plt.show()
    

    seaborn kdeplot and boxplot