Display displot in separate subplots - Seaborn

Viewed 569

I'm aiming to insert a Seaborn display into separate subplots. Using below, I want to pass Label1 to ax1 and Label2 to df2. However, I'm getting a warning: UserWarning: displot is a figure-level function and does not accept the ax= paramter. You may wish to try histplot. warnings.warn(msg, UserWarning)

Is there a way around this? I've had issues with histplot previously in regards to the hue parameter. I'm reluctant to use that if necessary.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fig, (ax1, ax2) = plt.subplots(1,2, figsize = (12,6))

df = pd.DataFrame({      
    'Num' : [1,2,1,2,3,2,1,3,2,2,1,2,3,3,1,3],
    'Label1' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],  
    'Label2' : ['D','E','D','F','E','D','F','E','F','D','E','F','E','D','D','F'],   
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })

ax1 = sns.displot(data = df, 
               x = 'Label1', 
               hue = 'Num',
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               shrink = 0.9, 
               discrete = True,
               aspect = 4, 
               height = 2,
               ax = ax1
               )

ax2 = sns.displot(data = df, 
               x = 'Label2', 
               hue = 'Num',
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               shrink = 0.9, 
               discrete = True,
               aspect = 4, 
               height = 2,
               ax = ax2
               )
1 Answers

If you want to avoid histplot(), I think the closest you can get with displot() is to melt() the data and use col to put Label1 and Label2 into two columns:

sns.displot(
    data = df.melt(['Num', 'Item'], var_name='Group', value_name='Label'),
    y = 'Label',
    hue = 'Num',
    row = 'Item',
    col = 'Group',
    row_order = ['Up', 'Down', 'Left', 'Right'],
    shrink = 0.9,
    discrete = True,
    aspect = 4,
    height = 2,
)

displot with 2 cols

Related