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

如何在Seaborn的FacetGrid中使用plt.fill_between填充线间区域?

在Seaborn FacetGrid中填充两条线之间区域的正确方法

你遇到的AttributeError: 'FacetGrid' object has no attribute 'get_lines'是因为get_lines()是单个Axes(子图)对象的方法,不能直接调用在整个FacetGrid上。要在FacetGrid的每个子图中填充置信区间,正确的做法是自定义绘图函数,将线条绘制和填充逻辑封装后,通过map_dataframe应用到每个子图。

修改后的完整代码

import seaborn as sns
import matplotlib.pyplot as plt

# 自定义绘图函数,包含线条绘制和区间填充
def plot_with_fill(data, **kwargs):
    # 绘制Shock主线
    sns.lineplot(data=data, x="Time", y="Shock", color='black', **kwargs)
    # 绘制上下置信线
    sns.lineplot(data=data, x="Time", y="Upper confidence level", color='grey', **kwargs)
    sns.lineplot(data=data, x="Time", y="Lower confidence level", color='grey', **kwargs)
    # 填充上下置信区间之间的区域
    plt.fill_between(data["Time"], data["Lower confidence level"], data["Upper confidence level"], color='grey', alpha=0.5)
    # 添加y=0的参考虚线
    plt.axhline(y=0, ls='--', c='red')

# 初始化绘图样式和FacetGrid
sns.set_style('white')
sns.set(font_scale=1.5, rc={"lines.linewidth": 1.5})

g = sns.FacetGrid(final, col="Variable", col_wrap=3, legend_out=True)
g.fig.set_figwidth(20)
g.fig.set_figheight(10)

# 将自定义函数应用到每个子图
g.map_dataframe(plot_with_fill)

# 设置子图标题和y轴范围
g.set_titles(col_template="{col_name}")
g.set(ylim=(-0.1, 0.1))

plt.show()

关键说明

  • 自定义函数plot_with_fill会接收每个子图对应的分片数据集,在当前子图的Axes上下文内完成所有绘图操作,确保填充逻辑只作用于当前子图的正确数据。
  • 直接使用数据集中的列作为fill_between的参数,无需通过get_lines()提取线条数据,逻辑更清晰且避免跨子图的错误。
  • 所有子图需要的绘图逻辑(主线、置信线、填充、参考线)都封装在一个函数中,通过map_dataframe统一应用,符合FacetGrid的设计逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:40:28