如何用Matplotlib为箱线图背景填充分层颜色?
为Seaborn箱线图添加Y轴分层背景色
问题说明
现有一段用Seaborn绘制铅含量按站点分布的箱线图代码,希望参考R绘制的带分层颜色背景的箱线图,为当前箱线图的Y轴方向添加分层背景色,尝试plt.fill_between未成功,寻求解决办法。
原代码:
# Importing necessary libraries import matplotlib.pyplot as plt import seaborn as sns # Size of the plot in inches plt.figure(figsize=(11, 6)) # Boxplot of the data ax = sns.boxplot(x="CÓD. ESTAÇÃO", y="CHUMBO", data=df, linewidth=1, palette='Blues') # Adjusting the y-axis range ax.set_ylim(min(df['CHUMBO']) - 0.01, max(df['CHUMBO']) + 0.01) # Adding title to the plot plt.title("Boxplot of lead content by station", loc="center", fontsize=18) plt.xlabel("Station Codes") plt.ylabel("Lead Content") ax.set_ylim(0, 0.045) # Displaying the plot plt.show()
解决方案
使用Matplotlib的ax.axhspan()函数绘制水平背景色块,该函数专门用于创建Y轴方向的水平跨度填充,比fill_between更适配这种分层背景需求。
修改后的代码
# Importing necessary libraries import matplotlib.pyplot as plt import seaborn as sns # Size of the plot in inches plt.figure(figsize=(11, 6)) ax = plt.gca() # 获取当前坐标轴对象 # 绘制Y轴分层背景色(顺序从下到上,zorder设为0确保在箱线图下方) # 分层区间和颜色可根据需求调整 ax.axhspan(0, 0.01, facecolor='#E8F4F8', zorder=0) ax.axhspan(0.01, 0.02, facecolor='#C6E4EF', zorder=0) ax.axhspan(0.02, 0.03, facecolor='#9DCBE3', zorder=0) ax.axhspan(0.03, 0.045, facecolor='#73AFD8', zorder=0) # 绘制箱线图,zorder=1确保在背景上方 ax = sns.boxplot(x="CÓD. ESTAÇÃO", y="CHUMBO", data=df, linewidth=1, palette='Blues', zorder=1) # 设置Y轴范围 ax.set_ylim(0, 0.045) # 添加标题与坐标轴标签 plt.title("Boxplot of lead content by station", loc="center", fontsize=18) plt.xlabel("Station Codes") plt.ylabel("Lead Content") # 显示图表 plt.show()
关键说明
ax.axhspan(y_min, y_max, facecolor=颜色, zorder=层级):指定Y轴起止区间并填充对应颜色,zorder=0让背景处于最底层,箱线图设置zorder=1确保显示在背景之上。- 分层区间和颜色可根据实际需求修改,比如参考R图的层级划分调整数值和配色。
- 先绘制背景再绘制箱线图,避免背景覆盖图表元素。
内容的提问来源于stack exchange,提问作者gongmaodu
相关产品推荐
相关产品推荐

