[Chartjs]-React chart2js Line chart with multiple datasets overlapping

1👍

For the object notation to work chart.js needs values to plot them against (not the index in the array) so you cant just provide an array containing only the value l.

You can either provide a labels array containing increasing numbers to which you match it or remove it and set your x scale to linear.

Labels example:

var options = {
  type: 'line',
  data: {
    labels: [0, 1, 2, 3],
    datasets: [{
        label: '# of Votes',
        data: [{
          x: 0,
          y: 4
        }, {
          x: 1,
          y: 6
        }, {
          x: 2,
          y: 2
        }],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [{
          x: 2,
          y: 2
        }, {
          x: 3,
          y: 3
        }],
        borderColor: 'blue'
      }
    ]
  },
  options: {
    scales: {}
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

Linear example:

var options = {
  type: 'line',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          x: 0,
          y: 4
        }, {
          x: 1,
          y: 6
        }, {
          x: 2,
          y: 2
        }],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [{
          x: 2,
          y: 2
        }, {
          x: 3,
          y: 3
        }],
        borderColor: 'blue'
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'linear'
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

Leave a comment