这是我的示例数据
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()
结果: 我的问题是:“有没有更简单的方法可以达到如下所示的相同结果?”
sns.stripplot(x=['pro1', 'pro2', 'pro3'], y='pro4', hue = [0,1], data=df)
最佳答案
import seaborn as sns
sns.catplot(df.melt('pro4'), x='variable', y='pro4',
hue='variable', col='value',
kind='strip')
输出:
关于python - 如何创建具有多个子图的带状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77492044/