python - 带状图中的颜色标记由与色调不同的变量表示

标签 python plot seaborn stripplot

我在条形图之上制作了一个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))

但是,我希望条形图的标记按性别着色(而不是像现在那样按条件着色),这是数据框中的另一列。我仍然希望它们按hue='Condition'分组。这可能吗?

plot here

最佳答案

您可以创建两个 strip 图,每个性别各一个,并将它们绘制为同一点。图例的双重条目可以通过 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

关于python - 带状图中的颜色标记由与色调不同的变量表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67930021/

相关文章:

python - 处理 PDF 以进行信息提取

python - 使用 matplotlib 绘制地震摆动轨迹

R:使用 d*ply 的多个 ggplot2 绘图

matlab - MATLAB 中的 xkcd 样式图

python - 如何使用 Matplotlib/Seaborn 并排绘制两个堆叠直方图

scipy - 如何用seaborn拟合泊松分布?

python - 在matplotlib中绘制相关图

python - 为什么 eval 函数中的 lambda 无法关闭用户定义的 'locals' 字典中的变量?

python - 加载图形然后用它来构建 tflite?

python ,Seaborn : Plotting frequencies with zero-values