为seaborn.boxplot中的特定框指定颜色

cls*_*udt 7 plot matplotlib seaborn

我大致如下调用seaborn.boxplot:

   seaborn.boxplot(ax=ax1,
                    x="centrality", y="score", hue="model", data=data], 
                    palette=seaborn.color_palette("husl", len(models) +1),
                    showfliers=False, 
                    hue_order=order,
                    linewidth=1.5)
Run Code Online (Sandbox Code Playgroud)

是否可以通过赋予特定颜色使一个盒子脱颖而出,同时用给定的调色板着色所有其他盒子?

在此输入图像描述

tmd*_*son 17

使用的盒子sns.boxplot实际上只是matplotlib.patches.PathPatch物体.它们ax.artists以列表形式存储.

因此,我们可以通过索引特别选择一个框ax.artists.然后,您可以设置facecolor,edgecolor以及linewidth许多其他属性.

例如(基于此处的一个示例):

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
                 data=tips, palette="Set3")

# Select which box you want to change    
mybox = ax.artists[2]

# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mit*_*len 6

Seaborn 在底层使用 Matplotlib。在 matplotlib 3.5 中,框存储在boxes而不是artists.

因此,您可以像这样设置框的颜色:

ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
                 data=tips, palette="Set3")

# Select which box you want to change    
mybox = ax.patches[2] # `patches` instead of `artists`

# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)
Run Code Online (Sandbox Code Playgroud)