问题
First of all, I apologize if my question is a slightly the same as others question. I searched for a solution and found 3 similar questions, yet none of them worked in my case, because the examples I found use Chart.js v1.
I saw a sample using a function placed in scaleLabel
to format the numbers just like this:
var options = {
animation: false,
scaleLabel: function(label){
return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
};
The above code, however, doesn't work anymore in the new Chart.js v2.
How can I format the scale numbers in Chart.js v2?
Here is my code: https://jsfiddle.net/2n7xc7j7/
回答1:
When adding option configurations, you need to make sure you nest the settings in the right sections. You can format the scale numbers by adding a callback
function to the yAxes
ticks configuration section:
options = {
scales: {
yAxes: [{
ticks: {
callback: function(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
}]
}
};
JSFiddle Demo: https://jsfiddle.net/2n7xc7j7/1/
回答2:
I did this:
http://profwtelles.ddns.net/grafico2.html
var canvas = document.getElementById('chart');
new Chart(canvas, {
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [{
label: 'A',
yAxisID: 'A',
data: [100, 96, 84, 76, 69]
}, {
label: 'B',
yAxisID: 'B',
data: [1, 1, 1, 1, 0]
}]
},
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 1,
min: 0
}
}]
}
}
});
I hope to help you. Best Regards
来源:https://stackoverflow.com/questions/37630102/how-to-format-scale-numbers-in-chart-js-v2