提问人:jacobdavis 提问时间:11/16/2023 最后编辑:Trenton McKinneyjacobdavis 更新时间:11/18/2023 访问量:78
如何创建具有多个子图的带状图 [duplicate]
How to create a stripplot with multiple subplots [duplicate]
问:
这是我的示例数据
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)
答:
评论