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

如何基于动态数据集构建Chart.js折线图?

动态生成Chart.js多折线图的Datasets

核心思路就是把后端返回的数据按accountStatus分组,再循环生成每条折线对应的dataset对象,完美适配不确定的折线数量。

1. 先处理数据分组

先把原始数据按状态分类,同时提取所有唯一日期作为X轴标签:

// 假设这是后端返回的原始数据
const rawData = [
  { "date": "2024-01-01", "accountStatus": "Active", "value": 120 },
  { "date": "2024-01-01", "accountStatus": "Inactive", "value": 30 },
  { "date": "2024-01-02", "accountStatus": "Active", "value": 135 },
  { "date": "2024-01-02", "accountStatus": "Inactive", "value": 25 },
  { "date": "2024-01-02", "accountStatus": "Suspended", "value": 10 },
  { "date": "2024-01-03", "accountStatus": "Active", "value": 140 },
  { "date": "2024-01-03", "accountStatus": "Inactive", "value": 22 },
  { "date": "2024-01-03", "accountStatus": "Suspended", "value": 15 }
];

// 提取所有唯一日期并按时间排序,作为X轴标签
const dates = [...new Set(rawData.map(item => item.date))].sort((a, b) => new Date(a) - new Date(b));

// 按accountStatus分组存储数据
const groupedData = {};
rawData.forEach(item => {
  if (!groupedData[item.accountStatus]) {
    groupedData[item.accountStatus] = [];
  }
  groupedData[item.accountStatus].push(item);
});

2. 准备颜色池

给每条折线分配不同颜色,准备一个足够多的颜色数组,不够的话循环复用:

const colorPool = [
  '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
  '#FF9F40', '#C9CBCF', '#E7E9ED', '#434343'
];

3. 动态生成Datasets

遍历每个状态分组,生成对应的dataset对象,同时补全每个日期的数据:

let datasets = [];
let colorIndex = 0;

// 遍历每个状态分组
Object.keys(groupedData).forEach(status => {
  // 为当前状态生成对应每个日期的数值,无数据的日期可填0(折线连到0)或null(折线断开)
  const dataPoints = dates.map(date => {
    const match = groupedData[status].find(item => item.date === date);
    return match ? match.value : 0;
  });

  // 将当前状态的配置加入datasets数组
  datasets.push({
    label: status,
    data: dataPoints,
    borderColor: colorPool[colorIndex % colorPool.length],
    backgroundColor: `${colorPool[colorIndex % colorPool.length]}20`, // 半透明填充色
    fill: false,
    tension: 0.1
  });

  colorIndex++;
});

4. 初始化Chart.js图表

把生成的日期标签和datasets直接传入图表配置:

const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'line',
  data: {
    labels: dates,
    datasets: datasets
  },
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'YYYY-MM-DD'
        },
        title: {
          display: true,
          text: '日期'
        }
      },
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: '数值'
        }
      }
    }
  }
});

关键注意点

  • 使用type: 'time'的X轴时,需要引入Chart.js的时间适配器(比如chartjs-adapter-date-fns),不想用的话直接用字符串日期当标签也可以。
  • 无数据的日期,填0会让折线连到原点,填null会让折线在该位置断开,可根据需求调整。
  • 颜色池数量不足时,通过取模操作循环复用颜色,保证每条折线颜色不重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:25:26