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

为含彩色背景层的Python箱线图添加图例的技术求助

解决方案:手动创建补丁(Patch)添加背景层图例

axhspan生成的背景矩形默认不会被自动纳入图例,因此需要手动创建与背景层样式匹配的补丁对象,再将这些补丁关联到图例中,以此实现类似R语言的图例效果。

具体实现步骤

  • 绘制箱线图和axhspan背景层时,同步记录每个背景的颜色、透明度和对应标签
  • 用matplotlib.patches.Patch创建与背景层样式一致的补丁对象
  • 调用ax.legend(),将补丁列表和标签列表传入完成图例添加

完整代码示例

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from matplotlib.patches import Patch

# 模拟2017-2022年溶解铁数据
years = [2017, 2018, 2019, 2020, 2021, 2022]
data = {year: np.random.normal(loc=(year-2016)*0.8 + 4, scale=1.2, size=120) for year in years}
df = pd.DataFrame(data)

# 绘制箱线图
fig, ax = plt.subplots(figsize=(10, 6))
sns.boxplot(data=df, ax=ax, palette="Set2")

# 定义三层背景区域的参数(y轴范围、颜色、标签)
bg_configs = [
    (0, 3, "#c7e9c0", "低浓度区间"),
    (3, 6, "#fff9c4", "中浓度区间"),
    (6, 9, "#ffccbc", "高浓度区间")
]

# 添加背景层
for y_min, y_max, color, label in bg_configs:
    ax.axhspan(y_min, y_max, color=color, alpha=0.3)

# 创建匹配背景样式的补丁列表
legend_patches = [Patch(color=color, alpha=0.3, label=label) for _, _, color, label in bg_configs]

# 添加图例,可通过bbox_to_anchor调整位置避免遮挡主图
ax.legend(handles=legend_patches, loc="upper right", bbox_to_anchor=(1.18, 1))

ax.set_ylabel("溶解铁浓度")
ax.set_title("2017-2022年溶解铁浓度分布箱线图")
plt.tight_layout()
plt.show()

样式调整说明

  • 若要贴近R语言图例的边框样式,可给Patch添加edgecolor="gray", linewidth=0.5参数,让补丁带边框
  • 保持Patch的alpha值与axhspan一致,确保图例颜色和背景层视觉匹配
  • 通过bbox_to_anchor参数灵活调整图例位置,避免遮挡箱线图的关键数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:32:46