【问题标题】:Changing hatch color in matplotlib在 matplotlib 中更改阴影颜色
【发布时间】:2025-11-23 05:15:01
【问题描述】:

感谢您帮助我正确地制作此图表!

我现在有另一个问题,我希望将阴影线的颜色更改为灰色。

我正在使用 matplotlib 版本 1.5.3'。我试过 mlp.rcParams['hatch.color'] = 'k'

但是好像不行……

这是我已经拥有的图的代码,谢谢:


import seaborn as sns
import matplotlib.pyplot as plt
mypallet = sns.color_palette([(190/256,7/256, 18/256),(127/256, 127/256, 127/256)])
import itertools
import numpy as np

plt.rcParams['figure.figsize'] = 7, 5
tips = sns.load_dataset("tips")
tips[(tips.day=='Thur') & (tips.sex=='Female') ] = np.nan
print(sns.__version__)
print(tips.head())
# Bigger than normal fonts
sns.set(font_scale=1.5)

ax = sns.swarmplot(x="day", y="total_bill", hue="sex",
                 data=tips, dodge=True, color='k')

#get first patchcollection
c0 = ax.get_children()[0]
x,y = np.array(c0.get_offsets()).T
#Add .2 to x values
xnew=x+.2
offsets = list(zip(xnew,y))
#set newoffsets
c0.set_offsets(offsets)

ax = sns.barplot(x="day", y="total_bill", hue="sex",
                 data=tips, capsize=0.1, alpha=0.8,
                 errwidth=1.25, ci=None, palette=mypallet)
xcentres = [0.2, 1, 2, 3]
delt = 0.2
xneg = [x-delt for x in xcentres]
xpos = [x+delt for x in xcentres]
xvals = xneg + xpos
xvals.sort()
yvals = tips.groupby(["day", "sex"]).mean().total_bill
yerr = tips.groupby(["day", "sex"]).std().total_bill

(_, caps, _)=ax.errorbar(x=xvals, y=yvals, yerr=yerr, capsize=4,
                         ecolor="red", elinewidth=1.25, fmt='none')
for cap in caps:
    cap.set_markeredgewidth(2)


handles, labels = ax.get_legend_handles_labels()
l = ax.legend(handles[0:2], labels[0:2]) # changed based on https://*.com/a/42768387/8508004
#sns.ax.ylim([0,60]) #original
ax.set_ylim([0,60]) # adapted from https://*.com/a/49049501/8508004 and change to legend
ax.set_ylabel("Out-of-sample R2") # based on https://*.com/a/46235777/8508004
ax.set_xlabel("") # based on https://*.com/a/46235777/8508004

for i, bar in enumerate(ax.patches):
    hatch = '///'
    bar.set_hatch(hatch)
    bar.set_x(bar.get_x() + bar.get_width()/2)
    break

我想将填充图案的颜色从黑色更改为灰色:(127/256, 127/256, 127/256)

【问题讨论】:

  • Hrm... 似乎很难分离边缘和阴影颜色*.com/a/38169221/6361531.. 但是你可以在你的补丁中使用'bar.set_edgecolor('k')'来更改第一个栏循环在底部。
  • 谢谢,成功了!以及影线宽度?
  • @user1748101 :由于您似乎是 Stack Overflow 的新手,您应该阅读 What should I do when someone answers my question?。具体来说,您应该对解决您的问题的所有答案(您尚未完成)进行投票,并接受最佳答案(您已完成)。

标签: python matplotlib seaborn


【解决方案1】:

添加 plt.rcParams['hatch.linewidth'] = 3 并使用 set_edgecolor,认为 `plt.rcParams['hatch.color'] = 'k' 不起作用是一个错误。

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
mypallet = sns.color_palette([(190/256,7/256, 18/256),(127/256, 127/256, 127/256)])
import itertools
import numpy as np

plt.rcParams['figure.figsize'] = 7, 5
plt.rcParams['hatch.linewidth'] = 3
tips = sns.load_dataset("tips")
tips[(tips.day=='Thur') & (tips.sex=='Female') ] = np.nan
print(sns.__version__)
print(tips.head())
# Bigger than normal fonts
sns.set(font_scale=1.5)

ax = sns.swarmplot(x="day", y="total_bill", hue="sex",
                 data=tips, dodge=True, color='k')

#get first patchcollection
c0 = ax.get_children()[0]
x,y = np.array(c0.get_offsets()).T
#Add .2 to x values
xnew=x+.2
offsets = list(zip(xnew,y))
#set newoffsets
c0.set_offsets(offsets)

ax = sns.barplot(x="day", y="total_bill", hue="sex",
                 data=tips, capsize=0.1, alpha=0.8,
                 errwidth=1.25, ci=None, palette=mypallet)


xcentres = [0.2, 1, 2, 3]
delt = 0.2
xneg = [x-delt for x in xcentres]
xpos = [x+delt for x in xcentres]
xvals = xneg + xpos
xvals.sort()
yvals = tips.groupby(["day", "sex"]).mean().total_bill
yerr = tips.groupby(["day", "sex"]).std().total_bill

(_, caps, _)=ax.errorbar(x=xvals, y=yvals, yerr=yerr, capsize=4,
                         ecolor="red", elinewidth=1.25, fmt='none')
for cap in caps:
    cap.set_markeredgewidth(2)


handles, labels = ax.get_legend_handles_labels()
l = ax.legend(handles[0:2], labels[0:2]) # changed based on https://*.com/a/42768387/8508004
#sns.ax.ylim([0,60]) #original
ax.set_ylim([0,60]) # adapted from https://*.com/a/49049501/8508004 and change to legend
ax.set_ylabel("Out-of-sample R2") # based on https://*.com/a/46235777/8508004
ax.set_xlabel("") # based on https://*.com/a/46235777/8508004

for i, bar in enumerate(ax.patches):
    hatch = '///'
    bar.set_hatch(hatch)
    bar.set_edgecolor('k')
    bar.set_x(bar.get_x() + bar.get_width()/2)
    break

输出:

【讨论】:

    【解决方案2】:

    AFAIK,阴影颜色由 edgecolor 属性决定,但问题是它也会影响条形的边框

    顺便说一句,我对代码末尾的循环感到困惑,我将其重写为:

    (...)
    ax.set_xlabel("") # based on https://*.com/a/46235777/8508004
    
    bar = ax.patches[0] #  modify properties of first bar (index 0)
    hatch = '///'
    bar.set_hatch(hatch)
    bar.set_x(bar.get_x() + bar.get_width()/2)
    bar.set_edgecolor([0.5,0.5,0.5])
    

    要更改影线的线宽,您似乎必须修改 rcParams。您可以将其添加到靠近脚本顶部的位置:

    plt.rcParams['hatch.linewidth'] = 3

    【讨论】:

    • 谢谢!改变边缘颜色没问题。现在我正在寻找一种改变边缘宽度的方法。
    • plt.rcParams['hatch.linewidth'] = 3,我已将其添加到我的答案中
    • 这仍然会改变我的阴影和条形边缘的颜色。我只想更改阴影颜色。
    【解决方案3】:
    plt.rcParams.update({'hatch.color': 'k'})
    

    【讨论】:

    • 欢迎来到 Stack Overflow!请edit your answer 包含对您的代码的解释,以及如何使用它来解决问题中描述的问题。这将有助于将来可能会遇到您的答案的其他人,并使他们更有可能发现它有用并为您投票:)
    【解决方案4】:

    对于可能还发现舱口未显示或颜色不正确的人来说,这只是两个额外的提示。

    首先,检查您是否在其他地方设置了一些边缘颜色。这似乎优先于指定的阴影颜色。 其次,如果你绘制一个补丁,使用facecolor而不是color。使用color,舱口将不可见:

    所以不是这样:

    from matplotlib.patches import Polygon, Patch
    fig, ax = plt.subplots()
    ax.legend(handles=[Patch(color='red', hatch='///')])  # no hatch visible 
    plt.show()
    

    改为:

    from matplotlib.patches import Polygon, Patch
    fig, ax = plt.subplots()
    ax.legend(handles=[Patch(facecolor='red', hatch='///')])  # hatch is now visible 
    plt.show()
    

    【讨论】: