Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Putting two seaborn distribution and boxplot side by side in Python

I would like to create two different Seaborn plots: a distribution plot and a boxplot, appearing side by side. This is the code I have:

import numpy as np
np.random.seed(3)
import seaborn as sns
import matplotlib.pyplot as plt
    
# Making age variable        
age = [7,5,8,5,1,2,5,8,5,5,5,2,6,8,8,2,3,8,25,3,82,8,2,6,29,3,1,5,10]
    
# create the figures
fig, ax = plt.subplots(1,2)
        
# boxplot
sns.boxplot(y = age, ax= ax[0]) 
  
# distribution plot        
sns.displot(age, kind = 'kde',color = 'red', 
                alpha = .1, fill = 'true',ax = ax[1])

# show plot
plt.show()

The code generates the following output:
Output from above code

Desired solution.
I would like to have the Distribution plot inside the second square. This code works if both plots are the same (e.g., both histograms for example). But I would like a distribution and a boxplot side by side. Is that possible? I really appreciate all the helps.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It happens because you’re using displot. If you run your code, you get a warning:
UserWarning: displot is a figure-level function and does not accept the ax= parameter. You may wish to try kdeplot. warnings.warn(msg, UserWarning)

You just need to replace your code from displot to kdeplot, something like the following:

sns.kdeplot(age, color = 'red', 
                alpha = .1, fill = 'true',ax = ax[1])

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading