[Chartjs]-How to specify ticks locations in chart.js?

6👍

Apparently with Chart.js v3, the accpted solution no longer works as expected. Trying afterBuildTicks as suggested by b1000 in his comment, it also didn’t work.

To make it work with afterBuildTicks, you need to map the number values into objects that have the property value each ([{ value: 0 }, { value: 3.5 }, ... ]). This can be done as follows:

afterBuildTicks: axis => axis.ticks = [0, 3.5, 5.7, 6.1].map(v => ({ value: v })) 

Please take a look at below runnable sample:

new Chart('line-chart', {
  type: 'scatter',
  data: {
    datasets: [{
      data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}],
      showLine : true,
      borderColor: '#1f77b4',
    }]
  },
  options: {
    scales: {
      x: {    
        min: 0,
        afterBuildTicks: axis => axis.ticks = [0, 3.5, 5.7, 6.1].map(v => ({ value: v })) 
      }
    }
  }
});
canvas {
  max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="line-chart"></canvas>

3👍

For not drawing grid lines on the chart, you need to add the following to your axes as described at Grid Line Configuration.

gridLines: {
  drawOnChartArea: false 
}

In order to obtain the ticks at the desired position only, you would define xAxis.ticks as shown below and documented at Tick Option and Creating Custom Tick Formats.

ticks: {
  ...       
  stepSize: 0.1,
  autoSkip: false,
  callback: value => [0, 3.5, 5.7, 6.1].includes(value) ? value : undefined,
  maxRotation: 0
},

Finally, to obtain a straight line between the data points, define lineTension: 0 on your dataset as explained at Line Styling.

Please have a look at your amended code below.

var config = {
  type: "line",
  data: {
    labels: [],
    datasets: [{
      data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}],
      fill: false,
      lineTension: 0,
      borderColor: "#1f77b4",
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'linear',
        ticks: {
          min: 0.,
          max: 7.,          
          stepSize: 0.1,
          autoSkip: false,
          callback: value => [0, 3.5, 5.7, 6.1].includes(value) ? value : undefined,
          maxRotation: 0
        },
        gridLines: {
          drawOnChartArea: false
        }
      }],
      yAxes: [{
        ticks: {
          showLabelBackdrop: true
        }, 
        gridLines: {
          drawOnChartArea: false
        }
      }]
    },
  },
};

new Chart('line-chart', config);
<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