Chart.js - Formatting Y axis

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

I'm using Chart.js to draw a simple bar plot and I need to format its Y axis like

123456.05 to 123 456,05 $

I don't understand how to use scaleLabel : "<%=value%>"

I saw someone pointing to "JS Micro-Templating",
but no clue how to use that with our scaleLabel option.

Does someone know how to format this Y axis, and maybe give me an example ?

回答1:

An undocumented feature of the ChartJS library is that if you pass in a function instead of a string, it will use your function to render the y-axis's scaleLabel.

So while, "<%= Number(value).toFixed(2).replace('.',',') + ' $' %>" works, you could also do:

scaleLabel: function (valuePayload) {     return Number(valuePayload.value).toFixed(2).replace('.',',') + '$'; } 

If you're doing anything remotely complicated, I'd recommend doing this instead.



回答2:

I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.

ticks: {     callback: function(label, index, labels) {         return label/1000+'k';     } } 

More in details

var options = {     scales: {         yAxes: [             {                 ticks: {                     callback: function(label, index, labels) {                         return label/1000+'k';                     }                 },                 scaleLabel: {                     display: true,                     labelString: '1k = 1000'                 }             }         ]     } } 


回答3:

scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>" 


回答4:

As Nevercom said the scaleLable should contain javascript so to manipulate the y value just apply the required formatting.

Note the the value is a string.

var options = {           scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>" }; 

jsFiddle example

if you wish to set a manual y scale you can use scaleOverride

var options = {           scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>",      scaleOverride: true,     scaleSteps: 10,     scaleStepWidth: 10,     scaleStartValue: 0  }; 

jsFiddle example



回答5:

Here you can find a good example of how to format Y-Axis value.

Also, you can use scaleLabel : "<%=value%>" that you mentioned, It basically means that everything between <%= and %> tags will be treated as javascript code (i.e you can use if statments...)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!