[Chartjs]-Chart.js – how to add a second data line to the line graph

0👍

In version 3.2.1 of Chart js;

myChart.data.datasets[myChart.data.datasets.length] = {
  label: "",
  xAxisID: "x-axis-2",
  data: newDataArray.map((val, index) => {x: labels[i], y: val}),
  fill: false,
  backgroundColor: "",
  borderColor: "",
  borderWidth: 1
}
myChart.update();

myChart.data.datasets.length can be set if you know the specific number of datasets(lines) you’re working with.

-1👍

If you want to do this in-line (you already have the data), you would add it to the “datasets” thus:

data: {
    labels: ["28/01/2018 15:07:34", "28/02/2018 12:31:27", "28/05/2018 01:21:28", "27/10/2018 01:21:28", "28/11/2018 05:09:28"],
    datasets: [{
        label: "title",
        backgroundColor: "transparent",
        borderColor: "#000",
        data: [65, 76, 32, 54, 43]
    },{
        label: "title2",
        backgroundColor: "transparent",
        borderColor: "#000",
        data: [50, 50, 50, 50, 50]
    }]
},

If you want to add data after the fact, you would push the dataset onto the data array as outlined here: https://www.chartjs.org/docs/latest/developers/updates.html

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

Leave a comment