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

如何在seaborn.barplot中为同色条形统一添加重复hatch填充图案

问题解决方法

你现有代码的问题是对bar.patches的排布逻辑理解有误:seaborn的柱状图会先排列同一个hue类别下的所有x轴分组条形,再排列下一个hue类别的条形。以你的示例为例:

  • x轴有2个分类(男性/女性),hue有3个分类(一等舱/二等舱/三等舱)
  • bar.patches的索引对应关系为:0=一等舱-男性、1=一等舱-女性、2=二等舱-男性、3=二等舱-女性、4=三等舱-男性、5=三等舱-女性
    你原逻辑按索引逐个取hatch,会导致每个条形的填充图案都不同,无法实现同hue同图案的需求。
调整后的完整代码
import matplotlib.pyplot as plt
import seaborn as sns
from itertools import cycle

# Set style
sns.set(style="whitegrid", color_codes=True)

# Load some sample data
titanic = sns.load_dataset("titanic")

# Make the barplot
bar = sns.barplot(x="sex", y="survived", hue="class", data=titanic)

# 定义和hue分类数量匹配的hatch列表
hatches = cycle([ "//" , "\\\\" , "|"])
# 获取x轴分类数量,每个hue类别下有对应数量的条形
x_group_count = len(bar.get_xticks())

# Loop over the bars
for idx, thisbar in enumerate(bar.patches):
    # 每x_group_count个条形切换一次hatch,保证同hue的条形图案一致
    if idx % x_group_count == 0:
        current_hatch = next(hatches)
    thisbar.set_hatch(current_hatch)

# 给图例也加上对应hatch,显示更统一
for patch, hatch in zip(bar.legend_.get_patches(), ["//" , "\\\\" , "|"]):
    patch.set_hatch(hatch)

plt.show()
代码说明
  • 核心调整逻辑是每x_group_count(也就是x轴的分组数量,本示例为2)个条形切换一次填充图案,保证同一个hue下的所有条形用同一种图案
  • 额外补充了图例的hatch设置逻辑,让图例和实际条形的填充图案保持一致,展示效果更统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:54:02