如何创建具有多个子图的带状图 [duplicate]

How to create a stripplot with multiple subplots [duplicate]

提问人:jacobdavis 提问时间:11/16/2023 最后编辑:Trenton McKinneyjacobdavis 更新时间:11/18/2023 访问量:78

问:

这是我的示例数据

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)

我想像这样在 seaborn 中制作 striplot(但在运行时实际上是错误的):

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

这是我的替代代码:

# 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()

结果:enter image description here我的问题是:“有没有更简单的方法可以像下面这样做相同的结果?

sns.stripplot(x=['pro1', 'pro2', 'pro3'], y='pro4', hue = [0,1], data=df)
蟒蛇 猫 Seaborn 带状图

评论


答:

3赞 mozway 11/16/2023 #1

在我看来,最简单的是融化猫图

import seaborn as sns

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

输出:

enter image description here

评论

1赞 jacobdavis 11/16/2023
对于我的问题来说,这是一个很好的简单解决方案。多谢
1赞 Scott Boston 11/16/2023
啊,是的,sns.catplot 是最好的解决方案。很棒的解决方案,@mozway!+1