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

基于Chart.js实现动态多折线图:从JSON生成可变数量折线

Dynamic Multi-Line Sales Chart with Chart.js (Variable Datasets)

Got it, let's build this flexible multi-line chart that adapts to any number of datasets from your JSON data. Here's a step-by-step solution tailored to your needs:

Step 1: Prepare the HTML Structure

First, add a canvas element where Chart.js will render the chart:

<canvas id="salesChart" width="800" height="400"></canvas>

Step 2: Process the Dynamic JSON Data

Your raw JSON data needs to be transformed into the format Chart.js expects. We'll extract the month labels (in order from Jan to Dec) and create a dataset for each name entry.

Here's the JavaScript code to handle this:

// Replace this with your actual database-fetched JSON data
const rawData = [
  {"name":"name1","jan":4067.5,"feb":1647, "mrz":1375,"apr":10191,"mai":0,"jun":28679,"jul":59502,"aug":0,"sep":0,"oct":0,"nov":0,"dec":0},
  {"name":"name2","jan":47548,"feb":63280.5, "mrz":51640.26,"apr":75029,"mai":41137,"jun":89114.26,"jul":77332,"aug":0,"sep":0,"oct":0,"nov":0,"dec":0},
  {"name":"name3","jan":38099,"feb":55023.5, "mrz":62668,"apr":39482,"mai":44193.3,"jun":52826.5,"jul":77072,"aug":0,"sep":0,"oct":0,"nov":0,"dec":0},
  {"name":"namex","jan":34930.5,"feb":36831.5, "mrz":24391,"apr":35051,"mai":38038,"jun":12700,"jul":51080,"aug":0,"sep":0,"oct":0,"nov":0,"dec":0}
];

// Define month keys in strict Jan-Dec order (matches your JSON's abbreviations)
const monthKeys = ["jan", "feb", "mrz", "apr", "mai", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
// Human-readable labels for the X-axis
const monthLabels = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Generate dynamic datasets for each name entry
const datasets = rawData.map((item, index) => {
  // Extract sales values in the correct month order
  const salesValues = monthKeys.map(key => item[key]);
  
  // Predefined color palette (cycles if you have more than 6 datasets)
  const colorPalette = [
    'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)'
  ];
  // Match border color to fill color (adjust opacity for contrast)
  const borderColor = colorPalette[index % colorPalette.length].replace('0.2', '1');

  return {
    label: item.name,
    data: salesValues,
    borderColor: borderColor,
    backgroundColor: colorPalette[index % colorPalette.length],
    fill: false,
    tension: 0.1 // Adds slight curve to lines for better readability
  };
});

Step 3: Initialize the Chart

Now we'll create the Chart.js instance with our processed data and configure the axes for clarity:

const ctx = document.getElementById('salesChart').getContext('2d');
new Chart(ctx, {
  type: 'line',
  data: {
    labels: monthLabels,
    datasets: datasets
  },
  options: {
    responsive: true, // Lets the chart adjust to container size
    scales: {
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: 'Sales Amount'
        }
      },
      x: {
        title: {
          display: true,
          text: 'Month'
        }
      }
    },
    plugins: {
      title: {
        display: true,
        text: 'Annual Sales Trend by Category'
      },
      legend: {
        position: 'top', // Places legend above the chart for better visibility
      }
    }
  }
});

Key Tips for Your Use Case:

  • Automatic Dataset Handling: The code will create a new line for every name in your JSON—no manual updates needed if the number of datasets changes.
  • Month Order Guarantee: By explicitly defining monthKeys, we ensure the X-axis always follows Jan-Dec, even if your JSON has months in a different order.
  • Color Flexibility: If you want more unique colors, you can replace the predefined palette with a random color generator function.
  • Dependency Note: Don't forget to include the Chart.js library in your project (add this to your HTML head):
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:06:36