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

Plotly绘制OLS趋势线结果异常(非线性、斜率不符)排查求助

问题根因

你遇到的趋势线异常是Plotly对时间类型x轴做OLS拟合的已知问题:当x轴为datetime格式时,Plotly会直接将其转换为纳秒级时间戳参与拟合,数值跨度过大导致计算精度异常,最终呈现出趋势线非线性、斜率不符合数据规律的错误表现。

修复代码

你可以新增一列数值类型的x轴特征用于拟合,示例如下:

import pandas as pd
import plotly.express as px

df=pd.DataFrame()
df['month'] = pd.to_datetime(['2020-04-01','2020-05-01','2020-06-01','2020-07-01','2020-08-01','2020-09-01','2020-10-01','2020-11-01','2020-12-01','2021-01-01','2021-02-01','2021-03-01'])
df['views']=[7942, 114511, 192292, 230733, 272823, 271613, 274803, 227554, 270407, 284185, 307765, 329814]
# 新增数值型x轴:距起始月份的间隔数
df['month_offset'] = (df['month'] - df['month'].min()).dt.days // 30

fig= px.scatter(
    df, 
    x='month', 
    y='views', 
    opacity=1,
    # 用数值列做趋势线拟合
    trendline='ols',
    trendline_x='month_offset',
    trendline_scope='overall'
)
fig.show()

运行后即可得到符合数据规律的线性OLS趋势线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:06:04