Chartjs-Displaying line chart for multiple datasets using chart.js

0👍

One way for achieving this, would be to defined data.labels as an array of numbers from 0 to 53.

labels: [0, 1, 2, ... 53]

The data inside the two datasets would then only contain the definitions of individual points.

data: [{ x: 46, y: 20 }, { x: 53, y: 94 }] // plandata 
...
data: [{ x: 8, y: 1}] // actualdata 

Here’s the JavaScript part that illustrates how the desired result can be obtained.

var plandata = [{ week: "46", planned_del: "20" }, { week: "53", planned_del: "94" }];
var actualdata = [{ week: "8", actual_del: "1" }];

new Chart("scurve_chart", {
  type: 'line',
  data: {
    labels: Array.from(new Array(54), (x, i) => i),
    datasets: [{
        label: "Planned Deliverables",
        fill: false,
        borderColor: "rgba(255, 0, 0, 1)",
        pointHoverBackgroundColor: "rgba(255, 0, 0, 1)",
        data: plandata.map(o => ({ x: Number(o.week), y: Number(o.planned_del)}))
      },
      {
        label: "Actual Deliverables",
        fill: false,
        backgroundColor: "rgba(0, 255, 0, 0.75)",
        borderColor: "rgba(0, 255, 0, 1)",
        pointHoverBackgroundColor: "rgba(0, 255, 0, 1)",
        pointHoverBorderColor: "rgba(0, 255, 0, 1)",
        data: actualdata.map(o => ({x: Number(o.week), y: Number(o.actual_del)}))
      }
    ]
  },
  options: {    
    tooltips: {
      callbacks: {
        title: (tooltipItem, data) => "Week " + data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index].x
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        ticks: {          
          min: 0,
          max: 53,
          stepSize: 1
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script> 
<canvas id="scurve_chart" height="90"></canvas>

Leave a comment