matplotlib 如何在箱线图后面添加灰色区域而不影响箱线图颜色[重复]

wooyq4lh  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(99)

这个问题已经有答案了

fill_between always below plot lines(1个答案)
上个月关门了。
我正在绘制一个箱线图,我想在箱线图后面添加一个灰色区域。但是,当我这样做时,箱线图变成灰色而不是黑色(见下图)。我可以做些什么来保持箱线图后面的灰色区域,而不影响它们的颜色(即,在这种情况下是黑色)?

sns.set(style="whitegrid",
        font_scale = 1.5)
fig, ax1 = plt.subplots(figsize=(6, 8))

min_value = 7*0.27
max_value = 7*1.77

# Fill the area between the minimum and maximum lines with grey on ax1
ax1.fill_betweenx([min_value, max_value], -0.5, 9.5, color='lightgrey', alpha=0.5)

# Create a second axis (ax2) for the boxplots on top of ax1
ax2 = sns.boxplot(data=Data,
            x="Diet type", 
            y="GW", 
            #hue="Diet",
            #whis = 0,
            width = 0.3,
            color = "black",
            showmeans = True,
            meanprops={"marker":"o",
                       "markerfacecolor":"red", 
                       "markeredgecolor":"black",
                      "markersize":"6"},
            ax = ax1,
            zorder = 1
            )

# Fill the area between the minimum and maximum lines with grey
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=90)
ax2.set_ylabel("Global Warming (kg CO2e/p/week)")
ax2.set_xlabel("")
ax2.set_ylim(0, 7*5.2)

plt.axhline(y=7*1.77, color='black', linestyle='-')
plt.axhline(y=7*0.81, color='black', linestyle='--')
plt.axhline(y=7*0.27, color='black', linestyle='-')

我试图将它们分成两个轴,并将箱线图的顺序定义为灰色区域的顶部,但我无法使其工作。
谢谢你,谢谢

kpbwa7wx

kpbwa7wx1#

解决方案

在调用ax1.fill_betweenx(...)时设置zorder=0,并将zorder=1保留在ax2中。解释性地定义两个轴的zorder可以解决这个问题!

代码

sns.set(style="whitegrid",
        font_scale = 1.5)
fig, ax1 = plt.subplots(figsize=(6, 8))

min_value = 7*0.27
max_value = 7*1.77

# Fill the area between the minimum and maximum lines with grey on ax1
ax1.fill_betweenx([min_value, max_value], -0.5, 9.5, color='lightgrey', alpha=0.5, zorder=0)

# Create a second axis (ax2) for the boxplots on top of ax1
ax2 = sns.boxplot(data=Data,
            x="Diet type", 
            y="GW", 
            #hue="Diet",
            #whis = 0,
            width = 0.3,
            color = "black",
            showmeans = True,
            meanprops={"marker":"o",
                       "markerfacecolor":"red", 
                       "markeredgecolor":"black",
                      "markersize":"6"},
            ax = ax1,
            zorder = 1
            )

# Fill the area between the minimum and maximum lines with grey
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=90)
ax2.set_ylabel("Global Warming (kg CO2e/p/week)")
ax2.set_xlabel("")
ax2.set_ylim(0, 7*5.2)

plt.axhline(y=7*1.77, color='black', linestyle='-')
plt.axhline(y=7*0.81, color='black', linestyle='--')
plt.axhline(y=7*0.27, color='black', linestyle='-')

相关问题