How to change the Y-axis values from numbers to strings in Chart.js?
I am using Chart.js and am trying to change the y-axis (see screen shot below). I tried filling the yLabels
property with an array of strings. But that didn't work. Any help would be appreciated!
jQuery(document).ready(function($) {
'use strict ';
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["HTML", "CSS", "SCSS", "JavaScript"],
yLabels: [
'newb',
'codecademy',
'code-school',
'bootcamp',
'junior-dev',
'mid-level',
'senior-dev',
'full-stack-dev',
'famous-speaker',
'unicorn'
],
datasets: [{
data: [12, 19, 3, 10],
backgroundColor: [
'rgba(255, 159, 64, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
// scales: {
// yAxes: [{
// ticks: {
// beginAtZero: true
// }
// }]
// },
title: {
display: true,
text: 'Shameless Bar Graph to show proficency in skills'
}
}
});
});
Solution 1:
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.