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

Matplotlib中仅为指定柱状图添加填充图案的简便方法

在Matplotlib柱状图中为特定类别柱子批量添加填充图案的解决方案

需求说明

寻找Matplotlib绘图中添加填充图案(hatch)的简便方法,仅为特定类别柱子(所有withCR_RF对应的浅蓝色柱子)添加填充图案,而非所有柱子,且不想手动逐个设置柱子属性。


数据示例(DataFrame部分内容)

target  withCR_RF   withCR_ET   withCR_LG   withCR_Ridge
0   partA   0.102   0.100   -0.3    -0.3
1   partB   0.081   0.085   -0.3    -0.3
2   part    -0.063  -0.050  -0.3    -0.3

尝试过程及遇到的问题

1. 初始绘图代码(无填充图案)

这是正常生成柱状图的基础代码,使用自定义颜色映射:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

cmap = ListedColormap(['#96C3EB', '#299438', '#B8B8B8', '#CCAC93'])
ax = df.plot.bar(x='target', colormap=cmap)

ax.set_xlabel(None)
ax.set_ylabel('prediction performance R²')
ax.set_title('comparing pipelines of prediction of executive function variables')
plt.xticks(rotation=45, ha='right')
plt.show()

2. 尝试直接设置hatch参数(无效)

尝试像设置颜色一样传入hatch列表,希望仅给第一类柱子加填充,但结果要么所有柱子都有图案,要么都没有:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

cmap = ListedColormap(['#96C3EB', '#299438', '#B8B8B8', '#CCAC93'])
hatches = ['++', '', '', '']
ax = df.plot.bar(x='target', colormap=cmap, hatch=hatches)

ax.set_xlabel(None)
ax.set_ylabel('prediction performance R²')
ax.set_title('comparing pipelines of prediction of executive function variables')
plt.xticks(rotation=45, ha='right')
plt.show()

3. 尝试遍历柱子但仅修改了一个(未批量生效)

参考建议后遍历柱子,但代码只修改了一个浅蓝色柱子,未覆盖所有withCR_RF对应的柱子:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

cmap = ListedColormap(['#96C3EB', '#299438', '#B8B8B8', '#CCAC93'])
ax = df.plot.bar(x='target', colormap=cmap)

ax.set_xlabel(None)
ax.set_ylabel('prediction performance R²')
ax.set_title('comparing pipelines of prediction of executive function variables')
plt.xticks(rotation=45, ha='right')

for lbl, patch in zip(ax.get_xticklabels() , ax.patches):
        if lbl.get_text() == 'withCR_RF':
            patch.set_hatch('*')
            patch.set_edgecolor(patch.get_facecolor())
            patch.set_facecolor('none')

plt.show()

4. 尝试索引多个柱子失败

尝试通过索引批量设置,但语法错误导致失败:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

cmap = ListedColormap(['#96C3EB', '#299438', '#B8B8B8', '#CCAC93'])
ax = df.plot.bar(x='target', colormap=cmap)
ax.patches[0,1,2,3].set_hatch('+') # 此处索引方式错误
ax.set_xlabel(None)
ax.set_ylabel('prediction performance R²')
ax.set_title('comparing pipelines of prediction of executive function variables')
plt.xticks(rotation=45, ha='right')
plt.show()

解决方案:批量为特定类别柱子添加填充图案

问题核心:df.plot.bar()生成的柱子按行分组排列,每个x轴标签对应一组4个柱子(对应4列数值数据)。withCR_RF对应的是每组的第0个柱子(索引从0开始)。

通过遍历ax.patches,按分组索引筛选目标柱子,批量设置填充图案:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

cmap = ListedColormap(['#96C3EB', '#299438', '#B8B8B8', '#CCAC93'])
ax = df.plot.bar(x='target', colormap=cmap)

# 获取每个x轴分组下的柱子数量(等于DataFrame数值列的数量)
n_cols = len(df.columns) - 1
# 遍历所有柱子,筛选出每组的第0个(对应withCR_RF列)
for i, patch in enumerate(ax.patches):
    if i % n_cols == 0:
        patch.set_hatch('++')
        # 可选:保留颜色同时添加图案,或设置空心+边框色
        # patch.set_edgecolor(patch.get_facecolor())
        # patch.set_facecolor('none')

ax.set_xlabel(None)
ax.set_ylabel('prediction performance R²')
ax.set_title('comparing pipelines of prediction of executive function variables')
plt.xticks(rotation=45, ha='right')
plt.show()

说明

  • n_cols为每个x轴分组下的柱子数量,此处因DataFrame有4个数值列,故n_cols=4
  • i % n_cols == 0筛选出每组的第一个柱子,即所有withCR_RF对应的柱子
  • 可修改set_hatch()的参数(如'*'、'xx'等)更换填充样式
  • 若要给其他列的柱子加图案,只需修改判断条件:比如给withCR_ET(每组第1个)加图案,改为i % n_cols == 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:57:47