Custom ticks in ChartsJS line plot

๐Ÿ‘:4

This can be done by defining an afterBuildTicks together with a ticks.callback function on the y-axis.

Please take a look at below runnable code and see how it works.

new Chart('my-chart', {
  type: 'line',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
    datasets: [{
      label: 'My Data',
      data: [65, 59, 80, 81, 56, 55, 40],
      borderColor: '#1f77b4'
    }]
  },
  options: {
    scales: {
      y: {    
         afterBuildTicks: axis => {
           let values = axis.ticks.map(t => t.value);
           let max = Math.max(...values);
           let min = Math.min(...values);
           axis.ticks = [
             { value: min + (max - min) * 0.25 },
             { value: min + (max - min) * 0.75 }
           ]
         },         
         ticks: {
           callback: (v, i) => i ? 'more' : 'less'
         }
      }
    }
  }
});
canvas {
  max-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="my-chart"></canvas>

Leave a comment