You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Seaborn双箱线图中的'rest'类别添加斜线填充(hatch='/')

给双箱线图的'rest'类别添加斜线填充

直接在绘制箱线图后,遍历子图的箱体元素,给对应'rest'类别的箱体设置斜线填充即可,完整代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

exercise = sns.load_dataset("exercise")

df1 = exercise.loc[(exercise["diet"] == "low fat"), :]
df2 = exercise.loc[(exercise["diet"] == "no fat"), :]

fig, axes = plt.subplots(1, 2)
# 绘制两个子图的箱线图
ax1 = sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[0], data=df1, showfliers=False)
ax2 = sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[1], data=df2, showfliers=False)

# 处理第一个子图的'rest'箱体
for patch, kind in zip(ax1.patches, df1['kind'].unique()):
    if kind == 'rest':
        patch.set_hatch('/')

# 处理第二个子图的'rest'箱体
for patch, kind in zip(ax2.patches, df2['kind'].unique()):
    if kind == 'rest':
        patch.set_hatch('/')

plt.show()

关键说明

  • Seaborn绘制的箱线图中,每个箱体都是Patch对象,存储在对应子图的patches列表里
  • 将箱体元素和对应类别标签一一配对,匹配到'rest'类别时,通过set_hatch('/')添加斜线填充样式
  • 两个子图分别遍历处理,确保各自的'rest'箱体都能被设置目标样式

内容的提问来源于stack exchange,提问作者Bugra Varol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:27:17