Display two line graphs with data starting at different points

Viewed 131

I have two data sets, with shared labels, but one data set is smaller than the other.

For instance:

label1: ['8-20', '8-21', '8-22', '8-23']
data1: [100, 120, 150, 170, 150]

label2: ['8-22', '8-23']
data2: [100, 120]

I want to display a line graph with both data sets, but start the second data set at the appropriate tick, instead of data2 starting at the same tick as data1.

Is this possible?

var thisChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: label1,
    datasets: [{ 
        data: data1,
        label: "LT15",
        borderColor: gradientStroke,
        backgroundColor: 'rgba(62, 205, 190, 0.1)',
        fill: true,
        spanGaps: true,
        tension: .2,
        borderWidth: 2,
      },{ 
        data: data2,
        label: "LT121",
        borderColor: gradientStroke2,
        backgroundColor: 'rgba(62, 149, 205, 0.2)',
        borderWidth: 2,
        fill: true,
        tension: .2,
        spanGaps: true
      }
    ]
  },
  options: {
    title: {
      display: false,
      text: 'Comparison'
    },
    responsive: true,
    maintainAspectRatio: false,
    legend: {
        lineWidth: 0,
    },
  }
});
1 Answers

You simply need to pad data2 with null, i.e.:

data2: [null, null, 100, 120]

var label1 = ['8-20', '8-21', '8-22', '8-23'],
  data1 = [100, 120, 150, 170, 150],

  label2 = ['8-22', '8-23'],
  data2 = [null, null, 100, 120],

  gradientStroke = 'red',
  gradientStroke2 = 'blue',

  thisChart = new Chart(document.getElementById('chart'), {
    type: 'line',
    data: {
      labels: label1,
      datasets: [{
        data: data1,
        label: "LT15",
        borderColor: gradientStroke,
        backgroundColor: 'rgba(62, 205, 190, 0.1)',
        fill: true,
        spanGaps: true,
        tension: .2,
        borderWidth: 2,
      }, {
        data: data2,
        label: "LT121",
        borderColor: gradientStroke2,
        backgroundColor: 'rgba(62, 149, 205, 0.2)',
        borderWidth: 2,
        fill: true,
        tension: .2,
        spanGaps: true
      }]
    },
    options: {
      title: {
        display: false,
        text: 'Comparison'
      },
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        lineWidth: 0,
      },
    }
  });
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

Related