pythonpandasseabornsubplotstripplot

How to create a stripplot with multiple subplots


This is my example data

data = {'pro1': [1, 1, 1, 0],
        'pro2': [0, 1, 1, 1],
        'pro3': [0, 1, 0, 1],
        'pro4': [0.2, 0.5, 0.3, 0.1]}
df = pd.DataFrame(data)

I want to make striplot in seaborn like this (but actually wrong when running):

sns.stripplot(x=['pro1', 'pro2', 'pro3'], y='pro4', data=df)

This is my alternative code:

# Create a figure with two subplots that share the y-axis
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharey=True)

# List of column names
l = ['pro1', 'pro2', 'pro3', 'pro4']

# Subplot 1: Positive values
df1 = df.copy(deep=True)
for i in l:
    # Set values to pro4 only when the corresponding pro1, pro2, pro3 is 1
    df1[i] = df1.apply(lambda row: row['pro4'] if row[i] == 1 else None, axis=1)
df1.drop(['pro4'], axis=1, inplace=True)
sns.stripplot(data=df1, ax=ax1)
ax1.set_title('Positive Values')  # Add a title to the subplot

# Subplot 2: Zero values
df1 = df.copy(deep=True)
for i in l:
    # Set values to pro4 only when the corresponding pro1, pro2, pro3 is 0
    df1[i] = df1.apply(lambda row: row['pro4'] if row[i] == 0 else None, axis=1)
df1.drop(['pro4'], axis=1, inplace=True)
sns.stripplot(data=df1, ax=ax2)
ax2.set_title('Zero Values')  # Add a title to the subplot

# Show the plots
plt.show()

Result: enter image description here My questions are: "is there any more simple way to do for the same result like below?"

sns.stripplot(x=['pro1', 'pro2', 'pro3'], y='pro4', hue = [0,1], data=df)

Solution

  • In my opinion, the easiest is to melt and catplot:

    import seaborn as sns
    
    sns.catplot(df.melt('pro4'), x='variable', y='pro4', 
                hue='variable', col='value',
                kind='strip')
    

    Output:

    enter image description here