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

如何用Dygraph高亮并扩展时序数据中的缺失时间步长区域?

解决方案:高亮并扩展Dygraph时序数据的缺失区域

一、高亮缺失时间区域

Dygraph支持通过drawCallback钩子自定义绘制逻辑,我们可以利用这个功能检测数据中的时间间隔异常,然后在图表上绘制高亮矩形标记缺失区域。具体实现如下:

  1. 先计算固定时间步长(示例中为30分钟,对应1800000毫秒);
  2. 遍历数据点,对比相邻点的时间差,找出大于步长的间隔,确定缺失时间段的起止时间;
  3. 将时间转换为图表的像素坐标,用Canvas绘制半透明矩形高亮该区域。

修改后的代码示例:

var inputdata = "2024/03/28 16:00,8.3
"+"2024/03/28 16:30,8.8
"+"2024/03/28 17:00,9.2
"+"2024/03/28 18:30,9.8
"+"2024/03/28 19:00,9.0
"+"2024/03/28 19:30,7.2"

// 固定时间步长(示例为30分钟,单位:毫秒)
const expectedStep = 30 * 60 * 1000;

Dygraph.onDOMready(function onDOMready() {      
  g = new Dygraph(
        document.getElementById("div_g"),
        inputdata,
        {
          legend: 'always',
          visibility: [true],
          colors:['red'],  
          labels :["date","IN"],
          series: {
            "IN": {
              strokeWidth: 1
            },
          },
          // 自定义绘制回调,处理缺失区域高亮
          drawCallback: function(dygraph, is_initial) {
            if (!is_initial) return;
            
            const ctx = dygraph.canvas.getContext('2d');
            const data = dygraph.rawData_;
            const xAxis = dygraph.xAxis();
            
            for (let i = 1; i < data.length; i++) {
              const prevTime = data[i-1][0].getTime();
              const currTime = data[i][0].getTime();
              const timeDiff = currTime - prevTime;
              
              // 检测到缺失时间段
              if (timeDiff > expectedStep) {
                // 缺失区域的起始和结束时间
                const gapStart = prevTime + expectedStep;
                const gapEnd = currTime - expectedStep;
                
                // 转换为图表像素坐标
                const x1 = xAxis.toDomXCoord(new Date(gapStart));
                const x2 = xAxis.toDomXCoord(new Date(gapEnd));
                const y1 = 0;
                const y2 = dygraph.canvas.height;
                
                // 绘制半透明高亮矩形
                ctx.fillStyle = 'rgba(128,128,128,0.3)';
                ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
              }
            }
          }
        }
      );
});

二、扩展缺失区域的高亮范围

如果需要扩展缺失区域的高亮范围(比如在缺失时间段的前后各延伸一个步长),只需调整缺失区域的起止时间计算逻辑:

// 扩展缺失区域:前后各加一个固定步长
const gapStart = prevTime - expectedStep;
const gapEnd = currTime + expectedStep;

你也可以自定义扩展时长,比如延伸15分钟:

const extendDuration = 15 * 60 * 1000;
const gapStart = prevTime - extendDuration;
const gapEnd = currTime + extendDuration;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:20:38