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

Plotly JS线性回归置信区间填充不完整问题排查求助

Plotly JS 置信区间填充不完整问题修复

问题描述

使用Plotly JS绘制带置信区间的线性回归交互图时,数据及所有元素均可正常显示,但置信区间仅部分区域被填充——上下区间线条完整,却未填满两条线之间的全部空间,此前功能正常,修改后出现异常。

问题代码

let lower_trace = [];
let top_trace = [];

data.forEach(obj => { 
    lower_trace.push(obj['lower'])
    top_trace.push(obj['upper'])
});

let trace_low = {
    x: x_values,
    y: lower_trace,
    mode: 'lines',
    fill: 'tonexty',
    type: 'scatter',
    name : "low",
    line: {
        color:  '#d4e6f1'
    }
};

let trace_upper = {
    x: x_values,
    y: top_trace,
    mode: 'lines',
    fill: '',
    type: 'scatter',
    name : "high",
    line: {
        color:  '#d4e6f1'
    }
};

let traceArray = [];
traceArray.push(trace_upper);
traceArray.push(trace_low);

traceArray.push(fit); //Plots the trending line
dots = Object.values(traces);
dots.forEach(dot =>{
    traceArray.push(dot);   
}); //Plots the data as scatter

let layout = { 
    font: {size: 12},
    xaxis: {
        showgrid: true,
        title: 'PDI',
    },
    yaxis: {
        showgrid: true,
        title: 'Ro',
    },
    legend:{
        x: 1,
        y: 0.5
    }             
};
    
let config = {responsive: true}  
 
Plotly.newPlot('mySidebare', traceArray, layout, config);

问题原因

Plotly的fill: 'tonexty'功能是填充当前轨迹与数组中紧随其后的下一个轨迹之间的区域。你的代码中,将置信区间的两个轨迹添加到数组后立刻插入了趋势线fit,导致trace_low的下一个轨迹是趋势线而非trace_upper,因此填充范围错误。同时轨迹顺序与填充设置不匹配,进一步加剧了问题。

修复方案

  1. 保证置信区间轨迹连续相邻:将两个区间轨迹放在数组最前面,中间不插入任何其他轨迹(趋势线、散点等)。
  2. 正确设置填充指向:让两个区间轨迹中,前面的那个设置fill: 'tonexty',指向后面的区间轨迹,确保填充范围是上下区间之间。
  3. 确认x_values为严格递增顺序,避免因x轴数据混乱导致填充异常。

修改后的代码

let lower_trace = [];
let top_trace = [];

data.forEach(obj => { 
    lower_trace.push(obj['lower'])
    top_trace.push(obj['upper'])
});

// 调整置信区间轨迹的fill设置
let trace_low = {
    x: x_values,
    y: lower_trace,
    mode: 'lines',
    fill: '',
    type: 'scatter',
    name : "low",
    line: {
        color:  '#d4e6f1'
    }
};

let trace_upper = {
    x: x_values,
    y: top_trace,
    mode: 'lines',
    fill: 'tonexty', // 设置填充到下一个轨迹(trace_low)
    type: 'scatter',
    name : "high",
    line: {
        color:  '#d4e6f1'
    }
};

let traceArray = [];
// 先添加置信区间轨迹,确保两者连续相邻
traceArray.push(trace_upper);
traceArray.push(trace_low);

// 再添加其他轨迹
traceArray.push(fit);
dots = Object.values(traces);
dots.forEach(dot => traceArray.push(dot));

let layout = { 
    font: {size: 12},
    xaxis: {
        showgrid: true,
        title: 'PDI',
    },
    yaxis: {
        showgrid: true,
        title: 'Ro',
    },
    legend:{
        x: 1,
        y: 0.5
    }             
};
    
let config = {responsive: true}  
 
Plotly.newPlot('mySidebare', traceArray, layout, config);

也可以将trace_low放在前面,给trace_low设置fill: 'tonexty',填充效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:10:25