我正在做一个箱线图,我想在箱线图后面添加一个灰色区域。然而,当我这样做时,箱线图变得灰色而不是黑色(见下图)。 我可以做什么来保留箱线图后面的灰色区域而不影响它们的颜色(即本例中的黑色)?
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='-')
我尝试将它们分成两个轴,并将箱线图的顺序定义为灰色区域的顶部,但我无法使其工作。
谢谢!
调用
zorder=0
时设置 ax1.fill_betweenx(...)
,并将 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='-')