繁体   English   中英

如何在 seaborn 中有效地设置分组箱线图的边缘和胡须?

[英]How to set the edge and whisker of grouped boxplot efficiently in seaborn?

我正在尽力绘制类似于以下内容的分组箱线图。 盒子里没有填充物,不同类型的晶须和边缘有不同的colors:

目标.png

示例代码:

  • 为箱线图生成 dataframe
x, y, category = list(), list(), list()
for i in range(5):
    for j in range(10):
        for k in ['Yes', 'No']:
            x.append(i)
            y.append(np.random.rand(1)[0])
            category.append(k)

df_for_boxplot = pd.DataFrame({
    'X': x,
    'Y': y,
    'category': category
})
  • 盒子 plot 与 seaborn
sns.set_theme(style="ticks", palette="pastel")
ax = sns.boxplot(x="X", y="Y", data=df_for_boxplot,
                 hue="category", 
                 # boxprops={"edgecolor": "r"}, # This makes all edges turn blue but I wanna set different catograys in different color.
                 palette=['w','w'],
                 whiskerprops={'linestyle':'--'}, showcaps = False)

# Select some boxes in particular by indexing ax.artists and set the edgecolor
[ax.artists[i].set_edgecolor('r') for i in [0,2,4,6,8]]
[ax.artists[i].set_edgecolor('b') for i in [1,3,5,7,9]]

# I can also change the color of specific line but it can only be set artificially.:
ax.lines[0].set_color('r')

ax.legend(loc='upper left')

我只能通过索引 ax.artists 和 ax.lines 手动设置边缘和胡须的颜色,因为我不知道如何统一设置不同类别的框。 当图像中的框太多或数据太复杂时,很难手动设置。

有没有更有效的解决方案? 任何建议,将不胜感激!

(我很抱歉无法发布图片,因为我是新来的,而且我的英语很差)

这里的优秀答案并没有解决问题。

我进行了一些研究,并将 box、fill 和其他行从 ax.Patches 更改为 PathPatch,并且我正在等待更精通此类事情的人的建议,以了解为什么不能在 ax 中解决它。艺术家。

fig, ax = plt.subplots(figsize=(12,9))

#sns.set_theme(style="ticks", palette="pastel")
sns.boxplot(x="X", y="Y",
            data=df_for_boxplot,
            hue="category", 
            # boxprops={"edgecolor": "r"}, 
            # palette=['w','w'],
            whiskerprops={'linestyle':'--'},
            # showcaps=False,
            ax=ax
                )

p = 0
for box in ax.patches:
    #print(box.__class__.__name__)
    if box.__class__.__name__ == 'PathPatch':
        if p % 2 == 0:
            box.set_edgecolor('C1')
            box.set_facecolor('white')
            for k in range(6*p,6*(p+1)):
                ax.lines[k].set_color('C1')
            p += 1
        else:
            box.set_edgecolor('C0')
            box.set_facecolor('white')
            for k in range(6*p,6*(p+1)):
                ax.lines[k].set_color('C0')
            p +=1

for legpatch in ax.get_legend().get_patches():
    col = legpatch.get_facecolor()
    legpatch.set_edgecolor(col)
    legpatch.set_facecolor('None')
        
plt.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM