javascriptchart.jsangular-chart

Contrast chart.js datalabels colors with the background


Using Chart.js qnd Angular.chart, I have a stacked chart in which I'm using different colors, I want to put the number of each value inside the cart, so I'm making use of the Plugin Datalabels.

The problem is that my chart looks like this:

enter image description here

Where I have the dark blue I'd like the numbers to be white. But don't know how to achieve this.

This is my code:

$scope.Options = {
   ...
   plugins: {
        datalabels: {
            color: '#171d28',
            anchor: 'center',
            align: 'center',
            clamp: true
        }
   }
};

I tried putting the colors in an array, like this:

$scope.Options = {
   ...
   plugins: {
        datalabels: {
            //The first 2 colors as dark and the third one as white
            color: ['#171d28', '#171d28', '#fff'],
            anchor: 'center',
            align: 'center',
            clamp: true
        }
   }
};

But this way it apply the changes by bar! not by the color section.
It says in the datalabels page that you can add functions, but not very sure how: Link to datalabels page about color

Any help is welcome, Thanks in advance!


Solution

  • I've found the answer!
    based in the code from the link I put in the question.

    You need the names of the values given in the Series. This is my Series array right now:

    $scope.Series = ['Low Blue', 'Blue', 'Strong Blue'];
    

    We need to add a function to the datalabels.color, and in the function we'll indicate how to color the labels of the ones corresponding to "Strong Blue":

    plugins: {
        datalabels: {
             color: function(context) {
                 var index = context.dataIndex;
                 var value = context.dataset.data[index];
    
                 //Inside the "dataset" we look for the "labels" we are using
                 //and store them in a variable
                 var valueWhite = context.dataset.label;
    
                 //We make the condition: if a value of the label is "Strong blue"
                 //then we color this label 'white'
                 if(valueWhite === 'Strong Blue') {
                     return value = 'white';
                 } else {
                     //If it's any other label, we color it 'black'
                     return value = '#000';
                 }
             }
    }
    

    This way all the sections with a Strong blue as background will have color white, and the rest will be black.