Chartjs-How to fix the distance between horizontal points (x-axis) in chartJS

1👍

The way to control distance between points it to set the X and Y axis with a min, max, and step size so that they never change regardless of the number of points that are in the chart.

Here is an example that sets the scales so that they will never change. Regardless of how many points appear on the chart everything will stay the same.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3}, 
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
      showLine: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Fixed X and Y Axis',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }],
      yAxes: [{
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }]
    }
  }
});

Here is a codepen example that demonstrates what this looks like

Leave a comment