Seaborn stripplot中的颜色标记使用不同于色调的变量

2024-09-28 21:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在轴上有经验组的条形图顶部制作了一个Seaborn条形图,根据数据帧中的两种不同条件(目标存在或目标不存在)使用以下代码进行分组:

IZ_colors = ['#E1F3DC','#56B567']

ax1 = sns.barplot(data=IZ_df, x='Group', y='Time in IZ (%)', hue='Condition',
                  order=['Std_Ctrl','ELS_Ctrl','Std_CSDS','ELS_CSDS'], hue_order=['Empty','Aggressor'],
                  palette=IZ_colors)

hatches = ['','//']
# Loop over the bars
for bars, hatch in zip(ax1.containers, hatches):
    # Set a different hatch for each group of bars
    for bar in bars:
        bar.set_hatch(hatch)
        
            
sns.stripplot(data=IZ_df ,x='Group', y='Time in IZ (%)', hue='Condition', dodge=True,
              order=['Std_Ctrl','ELS_Ctrl','Std_CSDS','ELS_CSDS'], hue_order=['Empty','Aggressor'], 
              palette=IZ_colors, marker='o', size=7, edgecolor='#373737', linewidth=1, color='black',)

plt.legend(bbox_to_anchor=(1.35, 0.7))

但是,我希望条带图的标记按性别(而不是现在的情况)着色,这是数据框中的另一列。我仍然希望它们按色调和条件分组。这可能吗

plot here


Tags: 数据infororder条件huestd条形图
1条回答
网友
1楼 · 发布于 2024-09-28 21:25:17

您可以创建两个stripplots,每个性别一个,并将它们绘制为相同的点。图例的双条目可以通过get_legend_handles_labels()删除,并获取句柄和标签的子集

下面是一个使用泰坦尼克号数据集的示例:

import matplotlib.pyplot as plt
import seaborn as sns

titanic = sns.load_dataset('titanic')

IZ_colors = ['#E1F3DC', '#56B567']

ax1 = sns.barplot(data=titanic, x='class', y='age', hue='alive',
                  order=['First', 'Second', 'Third'], hue_order=['no', 'yes'],
                  palette=IZ_colors)

hatches = ['', '//']
for bars, hatch in zip(ax1.containers, hatches):
    for bar in bars:
        bar.set_hatch(hatch)
for sex, color in zip(['male', 'female'], ['orange', 'turquoise']):
    df_per_sex = titanic[titanic['sex'] == sex]
    sns.stripplot(data=df_per_sex, x='class', y='age', hue='alive',
                  order=['First', 'Second', 'Third'], hue_order=['no', 'yes'],
                  dodge=True, palette=[color] * 2,
                  marker='o', size=4, edgecolor='#373737', linewidth=1)
handles, labels = ax1.get_legend_handles_labels()
handles = [handles[0], handles[2]] + handles[4:]
labels = ['Male', 'Female'] + labels[4:]
ax1.legend(handles, labels, bbox_to_anchor=(1.01, 0.7), loc='upper left')
plt.tight_layout()
plt.show()

stripplot with different colors for non-hue column

相关问题 更多 >