我正在使用Chart.js并尝试更改y轴(请参阅下面的屏幕截图)。我尝试使用字符串数组填充yLabels
属性。但那并没有奏效。任何帮助将不胜感激!
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'
}
}
});
});
答案 0 :(得分:4)
yAxes
标签实际上存储在图表的options
中,而不是您data
。
如果您查看the docs(稍微向上滚动),您会看到必须编辑刻度线的callback
属性在options.scales.yAxes
。
// 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'
}
然后在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
}
}
}]
}
}
查看结果this jsFiddle。