[Chartjs]-How can I display a set amount of ticks on the Y Axis?

3đź‘Ť

you just need add the callback in the ticks,

<canvas id="myChart" width="400" height="400"></canvas>
<script src='Chart.js'></script>
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Date/MoonCenter', 'Date/MoonCenter', 'Date/MoonCenter'],
            datasets: [{
                label: 'Dataset 1', backgroundColor: window.chartColors.red,
                stack: 'Stack 0',
                data: [4, 12, 4, 8, 12, 4]
            }, {
                label: 'Dataset 1', backgroundColor: window.chartColors.blue,
                stack: 'Stack 1',
                data: [8, 8, 12, 4, 4, 12]
            }]
        },
        options: {
            scales: {
                yAxes: [
                    {
                        ticks: {
                            beginAtZero: true,
                            callback: function (label, index, labels) {
                                switch (label) {
                                    case 4:
                                        return 'negative';
                                    case 8:
                                        return 'positive';
                                    case 12:
                                        return 'neutral';
                                }
                            }
                        }
                    }
                ]
            }
        }
    });
</script>

0đź‘Ť

Additional to saul’s answer:
Just add max-settings to the y-axis.

ticks: {
  max: 12
}

You also have to do callbacks for the tooltip if you want to display “positive”, “negative” and “neutral” instead of 4, 8 and 12.

Leave a comment