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

如何在Plotly Express散点图中填充趋势线下方区域?

解决方案

你可以直接从已生成的Plotly图表对象中提取lowess趋势线的坐标数据,无需手动重新拟合,配合填充参数即可实现需求,完整实现代码如下:

import plotly.express as px

# 原有绘图逻辑
uk_age = df[df['CountryLive']=='United Kingdom']['Age'].mean()
fig = px.scatter(df, x=x, y=y, trendline="lowess", trendline_options=dict(frac=0.4), 
                 trendline_color_override="red",template='plotly_white', range_y=[0,30])
fig.add_vline(x=uk_age, annotation_text="UK", 
              annotation_position="top right", line_color="blue")

# 提取lowess趋势线的坐标数据,fig.data[0]是散点轨迹,fig.data[1]是趋势线轨迹
trend_x = fig.data[1].x
trend_y = fig.data[1].y

# ------------------- 需求1:填充整条趋势线下方区域 -------------------
# fig.add_scatter(
#     x=trend_x,
#     y=trend_y,
#     fill='tozeroy',
#     fillcolor='rgba(255, 0, 0, 0.2)', # 半透明红色,和趋势线颜色匹配
#     line=dict(color='transparent'), # 隐藏额外绘制的线条,避免和原有趋势线重叠
#     showlegend=False,
#     hoverinfo='skip'
# )

# ------------------- 需求2:仅填充垂直线右侧的趋势线下方区域 -------------------
# 筛选出x坐标大于等于UK平均年龄的趋势线数据
mask = trend_x >= uk_age
right_trend_x = trend_x[mask]
right_trend_y = trend_y[mask]

fig.add_scatter(
    x=right_trend_x,
    y=right_trend_y,
    fill='tozeroy',
    fillcolor='rgba(255, 0, 0, 0.2)',
    line=dict(color='transparent'),
    showlegend=False,
    hoverinfo='skip'
)

fig.show()

说明

  • 两个需求二选一即可,不需要的实现注释掉对应代码段就行
  • 填充颜色的透明度、颜色值可以根据需求自行调整rgba参数的数值
  • 该方法直接复用Plotly已生成的lowess拟合结果,和你原有趋势线的参数完全一致,不会出现拟合偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:27:03