python - 如何创建具有多个子图的带状图

标签 python pandas seaborn subplot stripplot

这是我的示例数据

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)

最佳答案

在我看来,最简单的是meltcatplot :

import seaborn as sns

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

输出:

enter image description here

关于python - 如何创建具有多个子图的带状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77492044/

相关文章:

python-3.x - 如何在 Seaborn 箱线图中调整 mustache 的大小?

python - 相关矩阵图,一侧是系数,另一侧是散点图,对角线分布

python - 如何使用 seaborn 绘制成对直方图

Python:比较不冗余的列表项

python - 如何在Mac上卸载pyenv(由homebrew安装)

python - pandas - 根据另一列中的值使用 bins 定义进行分箱

python - Pandas 分配回使用 notnull() 过滤的系列

python - 无法安装 Pandas (错误 : Cannot uninstall 'numpy' )

python - 为什么 subprocess.Popen 参数长度限制小于操作系统报告的长度?

python - 从 Django Rest 框架序列化器中查找模型名称