[Chartjs]-How to add labels for only some of the data point?

1👍

Yes, you can specify the ticks you want with the afterBuildTicks hook. You can also specify the count property in the ticks this will make it so chart.js generates that many ticks but you dont have control over the values of those ticks:

const data = [];

for (let i = 0; i < 100; i++) {
  data.push({
    x: i,
    y: i
  })
}

const options = {
  type: 'scatter',
  data: {
    datasets: [{
      label: '# of Votes',
      data: data,
      borderColor: 'orange',
      backgroundColor: 'orange'
    }]
  },
  options: {
    scales: {
      x: {
        afterBuildTicks: (a) => (a.ticks = [{
          value: 0
        }, {
          value: 25
        }, {
          value: 50
        }, {
          value: 75
        }, {
          value: 100
        }]),
        ticks: {
          count: 5, // limit to 4 ticks but let chart.js decide what tose ticks are
        }
      }
    }
  }
}

const 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.7.1/chart.js"></script>
</body>

Leave a comment