How to Create a Variable for Chart Js Datalabel Plugin Formatter
I Am Trying to Write a Global Formatting Variable for Chart Js Datalabels Plugin Across All the Charts I Create. Here Is My Attempt - Global Variable: Var...
I am trying to write a global formatting variable for chart js datalabels plugin across all the charts I create. Here is my attempt -
Global Variable:
var datalabels_format_sanssymb = {
function (value) {
if (value >= 1000000000 || value <= -1000000000) {
return (value / 1000000000).toFixed(1).replace(/\.0$/, '');
}
if (value >= 1000000 || value <= -1000000) {
return (value / 1000000).toFixed(1).replace(/\.0$/, '');
}
if (value >= 1000 || value <= -1000) {
return (value / 1000).toFixed(1).replace(/\.0$/, '');
}
return value;
}
}
And here is where I want to call the variable in the chart javascript:
plugins: {
datalabels: {
formatter: datalabels_format_sanssymb,
font: {
size: 10,
weight: 'bold'
},
color: '#333333'
}
},
This doesn't seem to work. Am I doing this correctly?
1 Answer
plugins.datalabels.formatter should be set to a function. You are setting it to an object. Change your definition so it doesn't include the leading { and trailing }:
var datalabels_format_sanssymb = function (value) {
if (value >= 1000000000 || value <= -1000000000) {
return (value / 1000000000).toFixed(1).replace(/\.0$/, '');
}
if (value >= 1000000 || value <= -1000000) {
return (value / 1000000).toFixed(1).replace(/\.0$/, '');
}
if (value >= 1000 || value <= -1000) {
return (value / 1000).toFixed(1).replace(/\.0$/, '');
}
return value;
}
See the plugin documentation for examples.