[Chartjs]-How to plot multiple time series in chartjs where each time series has different times

33👍

In ChartJS, label is a Category Cartesian Axis. Since you mentioned linear interpolation in your code, I assume the strings like 2017-01-06 18:39:30 are not categories, they represent the numeric values of the x-axis. So we need to inform ChartJS that the strings in the x axis are actually time. We do this in the scale options.

var s1 = {
  label: 's1',
  borderColor: 'blue',
  data: [
    { x: '2017-01-06 18:39:30', y: 100 },
    { x: '2017-01-07 18:39:28', y: 101 },
  ]
};

var s2 = {
  label: 's2',
  borderColor: 'red',
  data: [
    { x: '2017-01-07 18:00:00', y: 90 },
    { x: '2017-01-08 18:00:00', y: 105 },
  ]
};

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'line',
  data: { datasets: [s1, s2] },
  options: {
    scales: {
      xAxes: [{
        type: 'time'
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart"></canvas>

You can find more information in Chart.js documentation.

4👍

You can have data of the form [{x:”value”, y:”value”}] when your graph is of type scatter.

So to make your graph work, do this.

var canvas = document.getElementById("graph");
var s1 = [{x:"2017-01-06 18:39:30",y:"100"},{x:"2017-01-07 18:39:28",y:"101"}];
var s2 = [{x:"2017-01-07 18:00:00",y:"90"},{x:"2017-01-08 18:00:00",y:"105"}];

var graphParams = {
	type:"scatter",
	data:{
		datasets: [{
			label:"Series 1",
			data:s1,
			borderColor:"red",
			backgroundColor:"transparent",
		},
		{
			label:"Series 2",
			data:s2,
			borderColor:"blue",
			backgroundColor:"transparent",
		}],
	},
	options:{
		maintainAspectRatio:false,
		responsive:false,	
		scales:{
			xAxes:[{
				type:"time",
				distribution: "series",
			}],
		}
	}

}
ctx = new Chart(canvas, graphParams);
<canvas id="graph" height="500" width="700"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.min.js"></script>

Leave a comment