How to Limit the Number of Labels on a Line Chart in Chart.js ?

In this article, we will see two different approaches to control and limit the number of labels on the Line Chart in Chart.JS. We will see the practical implementation of these approaches with user interactive examples and their outputs.

Table of Content

  • Using maxTicksLimit Property
  • Using Callback

Chart.js CDN Link

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Approach 1: Using maxTicksLimit Property

In this approach, we are using the maxTicksLimit property which is in the options configuration. Using this property, we can control the number of x-axis labels that are displayed on the line chart. We have taken the input field and button, in which the user can enter the range, and according to that the labels are adjusted.

Syntax:

options: {
scales: {
x: {
ticks: {
maxTicksLimit: value
}
},
y: {
ticks: {
maxTicksLimit: value
}
}
}
}

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Example 1</title>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
    </script>
</head>
 
<body>
    <center>
        <h1 style="color: green;">
            w3wiki
        </h1>
        <h3>
            Approach 1: Using
            maxTicksLimit property
        </h3>
        <label for="ticksLimit">
            Set Ticks Limit:
        </label>
        <input type="number"
               id="ticksLimit"
               value="2"
               min="1" max="12">
        <button onclick="updateFn()">
            Update Chart
        </button>
        <canvas id="chart1"></canvas>
    </center>
    <script>
        let userInput =
            document.getElementById('ticksLimit');
        const data = {
            labels:
                ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datasets: [{
                label: 'Monthly Visitors',
                data:
                    [1200, 1500, 1800, 2000, 1700, 1900,
                        2200, 2500, 2800, 3000, 2700, 3200],
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 2,
                fill: false
            }]
        };
        const options = {
            scales: {
                x: {
                    ticks: {
                        maxTicksLimit: 2
                    }
                }
            }
        };
        const ctx = document.
            getElementById('chart1').getContext('2d');
        const chart1 = new Chart(ctx, {
            type: 'line',
            data: data,
            options: options
        });
        function updateFn() {
            const newLimit = parseInt(userInput.value);
            if (newLimit >= 1 && newLimit <= 12) {
                chart1.options.scales.x.
                    ticks.maxTicksLimit = newLimit;
                chart1.update();
            } else {
                alert('Ticks limit should be between 1 and 12.');
            }
        }
    </script>
</body>
 
</html>


Output:

Approach 2: Using Callback

In this approach, we are using the callback property within the options configuration. We are controlling the x-axis labels in the Line chart according to the user input in the input box. The chart adjusts the label intervals dynamically according to the user input.

Syntax:

const options = {
scales: {
x: {
ticks: {
callback: function(value, index, values) {
// logic
return modifiedLabel;
}
}
},
// other scale data
};

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Example 2</title>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
      </script>
</head>
 
<body>
    <center>
        <h1 style="color: green;">
            w3wiki
        </h1>
        <h3>
            Approach 2: Using Callbacks
        </h3>
        <label for="ticksLimit">
            Set Ticks Limit:
        </label>
        <input type="number"
               id="ticksLimit"
               value="2"
               min="1" max="12">
        <button onclick="updateFn()">
            Update Chart
        </button>
        <canvas id="chart2"></canvas>
    </center>
    <script>
        const originalData =
              [1200, 1500, 1800, 2000, 1700, 1900,
               2200, 2500, 2800, 3000, 2700, 3200];
        const data = {
            labels:
          ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
           'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datasets: [{
                label: 'Monthly Visitors',
                data: originalData,
                backgroundColor:
              'rgba(75, 192, 192, 0.2)',
                borderColor:
              'rgba(75, 192, 192, 1)',
                borderWidth: 2,
            }]
        };
        const options = {
            scales: {
                x: {
                    ticks: {
                        callback: function (value, index, values) {
                            const ticksLimit =
                                  document.getElementById('ticksLimit').value;
                            const interval =
                                  Math.ceil(values.length / ticksLimit);
                            return index % interval === 0 ? value : '';
                        }
                    }
                }
            }
        };
        const ctx =
                  document.getElementById('chart2').getContext('2d');
        const chart2 = new Chart(ctx, {
            type: 'line',
            data: data,
            options: options
        });
 
        function updateFn() {
            const newLimit =
                  parseInt(document.getElementById('ticksLimit').value);
            if (newLimit >= 1 && newLimit <= 12) {
                const interval =
                      Math.ceil(originalData.length / newLimit);
                chart2.data.datasets[0].data =
                  originalData.filter((_, index) => index % interval === 0);
                chart2.options.scales.x.ticks.callback =
                  function (value, index, values) {
                    return index % interval === 0 ? value : '';
                };
                chart2.update();
            } else {
                alert('Ticks limit should be between 1 and 12.');
            }
        }
    </script>
</body>
 
</html>


Output:



Contact Us