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

如何用Chart.js控制数据记录仪图表显示数据量并保留历史数据?

Chart.js固定显示20个数据点且保留历史数据的实现方法

核心思路:不删除旧数据,通过动态调整X轴的显示范围来控制只展示最近20个点,所有历史数据都保存在数组中,使用缩放插件时就能查看全部历史。

修改后的完整main.js代码

document.addEventListener('DOMContentLoaded', function () {
  const ctx = document.getElementById('chartCanvas').getContext('2d');

  const data = {
    labels: [],
    datasets: [{
      label: 'Value',
      data: [],
      borderColor: 'blue',
      backgroundColor: 'rgba(0, 0, 255, 0.1)',
    }]
  };

  const options = {
    title: {
      display: true,
      text: 'Live Data Logger',
    },
    legend: {
      position: 'bottom',
    },
    scales: {
      x: {
        type: 'linear',
        position: 'bottom',
        ticks: {
          stepSize: 1,
        },
      },
      y: {
        beginAtZero: true,
      }
    },
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      zoom: {
        zoom: {
          wheel: {
            enabled: true,
          },
          drag: {
            enabled: true,
          },
          mode: 'xy',
        },
        pan: {
          enabled: true,
          mode: 'x',
        }
      }
    }
  };

  const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options,
  });

  function addDataPoint() {
    const x = chart.data.labels.length;
    const y = Math.random() * 100;

    // 始终保留所有数据,不删除旧数据
    chart.data.labels.push(x);
    chart.data.datasets[0].data.push(y);

    // 数据超过20个时,动态设置X轴显示范围
    if (chart.data.labels.length > 20) {
      chart.options.scales.x.min = x - 19;
      chart.options.scales.x.max = x;
    } else {
      // 不足20个时恢复自动适配
      delete chart.options.scales.x.min;
      delete chart.options.scales.x.max;
    }

    chart.update('none');
  }

  setInterval(addDataPoint, 1000)

  const resetZoomButton = document.getElementById('resetZoomButton');
  resetZoomButton.addEventListener('click', function () {
    chart.resetZoom();
    // 重置后回到显示最近20个点的状态
    const latestX = chart.data.labels.length - 1;
    if (latestX >= 19) {
      chart.options.scales.x.min = latestX - 19;
      chart.options.scales.x.max = latestX;
    } else {
      delete chart.options.scales.x.min;
      delete chart.options.scales.x.max;
    }
    chart.update();
  });
});

关键修改点说明

  • 保留全量数据:彻底移除shift()删除逻辑,所有新增数据直接存入数组,历史数据不丢失。
  • 动态X轴范围:数据量超过20时,计算X轴最小显示值为当前最后一个X值-19,刚好展示20个连续点;数据不足时自动适配范围。
  • 优化更新体验:用chart.update('none')关闭动画,避免每秒新增数据的卡顿。
  • 重置缩放适配:点击重置按钮后,重新设置X轴范围,确保回到默认显示最近20个点的状态。
  • 开启平移功能:修改zoom插件pan配置为enabled: true,方便用户平移查看更早的历史数据。

效果验证

  • 常态下仅显示最近20个数据点。
  • 缩放/拖拽时可查看全部历史数据。
  • 重置缩放后自动回到默认显示状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:14:52