How to make ticks evenly spaced with chart.js?

by darrion.kuhn , in category: Javascript , 8 months ago

How to make ticks evenly spaced with chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 8 months ago

@darrion.kuhn 

To make ticks evenly spaced with Chart.js, you can use the autoSkip and maxTicksLimit options on the scale configuration. Here's an example of how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
  <title>Chart.js - Evenly Spaced Ticks</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <canvas id="myChart"></canvas>

  <script>
    // Generate some random data
    const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    const data = [10, 20, 30, 40, 50, 60];

    // Create the chart
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'My Dataset',
          data: data,
          fill: false,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.1
        }]
      },
      options: {
        scales: {
          x: {
            ticks: {
              autoSkip: true,
              maxTicksLimit: 5
            }
          }
        }
      }
    });
  </script>
</body>
</html>


In this example, we have a line chart with 6 data points, and we want to display only 5 evenly spaced ticks on the x-axis. Setting autoSkip to true enables automatic skipping of ticks if there are too many labels to fit on the axis. And maxTicksLimit limits the maximum number of ticks to 5.


You can adjust the maxTicksLimit value as per your requirement to control the spacing of the ticks on the x-axis.