[Chartjs]-How to change the Y-axis values from numbers to strings in Chart.js?

12👍

For version 2.x, yAxes labels are actually stored in the options of the chart, and not its data as you did.

If you take a look at the docs, you’ll see that you have to edit the callback attributes of the ticks in options.scales.yAxes .


To do what you want, I just added a JS object in your code :

// Replace the value with what you actually want for a specific key
var yLabels = {
    0 : 'newb', 2 : 'codecademy', 4 : 'code-school', 6 : 'bootcamp', 8 : 'junior-dev',
    10 : 'mid-level', 12 : 'senior-dev', 14 : 'full-stack-dev', 16 : 'famous-speaker',
    18 : 'unicorn', 20 : 'harambe'
}

And then in the callback :

options: {
    scales: {
        yAxes: [{
            ticks: {
                callback: function(value, index, values) {
                    // for a value (tick) equals to 8
                    return yLabels[value];
                    // 'junior-dev' will be returned instead and displayed on your chart
                }
            }
        }]
    }
}

Take a look at this jsFiddle for the result.

3👍

Update for the 3.9.1 version (see https://www.chartjs.org/docs/latest/axes/labelling.html#creating-custom-tick-formats). It’s quite similar but you will need to change the syntax to get :

options: {
        scales: {
            y: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, ticks) {
                        return '$' + value;
                    }
                }
            }
        }
    }

Leave a comment