Multiple line charts with independent data Javascript (Chart.js or google-vizualisation)

2👍

You can use a scatter chart, that accepts the data as an array of objects containing x and y properties. To turn it into a line chart, define showLine: true inside the data configuration objects.

Given your data structures, the following line of code produces the data structure expected by Chart.js.

data1.map(o => ({ x: o[0], y: o[1] }))

Please have a look at below runnable code snippet.

const data1 = [[0,1],[2,3],[5,7]];
const data2 = [[1,4],[2,6],[5,2],[7,1]]; 

new Chart('line-chart', {
  type: "scatter",
  responsive: true,
  data: {
    datasets: [
      {
        data: data1.map(o => ({ x: o[0], y: o[1] })),
        label: 'Dataset 1',
        showLine: true,
        fill: false,
        borderColor: 'red'
      },
      {
        data: data2.map(o => ({ x: o[0], y: o[1] })),
        label: 'Dataset 2',
        showLine: true,
        fill: false,
        borderColor: 'blue'
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>

Leave a comment