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 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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest