[Chartjs]-Chart.js v4 truncate scale/labels

2👍

To get/change the value of the label you have to use the function getLabelForValue.
(here an example from the documentation)

And split is the incorrect function you would need to use substring.
(link to the mdn documentation)

Here all the fixes entered into your example code:

new Chart(document.getElementById("chart"), {
    type: 'bar',
    data: { 
        labels: ["Test looooong 1", "Test looooong 2", "Test looooong 3"],
        datasets: [{ data: [574.48, 140.93, 64.37]}]
    },
    options: {
        scales: {
            y: {
                ticks: { callback: value => `$ ${value }` }
            },
            x: {
               ticks: { 
                   callback: function(value){
                       let newLabel = this.getLabelForValue(value)
                           .substring(0,8) + '...';
                       return newLabel;
                   }
               }
            }
        }
    }
});
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
   <canvas id="chart" ></canvas>
</div>

Information: The mentioned solutions don’t worked because, as far as I can tell, they are base on he chartjs Verion 2.0+, and since then the chartjs library change substantially.

Leave a comment