Chart.js: Change legend color to a desired color (so not the first color of dataset)

Created on 25 May 2018  ·  3Comments  ·  Source: chartjs/Chart.js

So the legend color is the first color of the dataset by default (at a bar chart as example).
How can I change the legend color to a color of choice?

Example:

"datasets": [{
    "label": "2016",
    "color": ["rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(23,223,23,0.5)", "rgba(23,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,223,23,0.5)", "rgba(255,23,23,0.5)", "rgba(255,23,23,0.5)"

The legend of dataset with label '2016' will get the first color of the dataset.
But thats pretty annoying, because if I use multiple datasets, with both red colors items as first item, both legends will be red

Most helpful comment

My solutuon:

With the dataset I and extra color code called'labelColor', and set it with this:

Chart.plugins.register({
    beforeDraw: function (chart) {
        if (chart.config.data.datasets[0].labelColor) {
            let legends = chart.legend.legendItems;
            legends.forEach(function (e, i) {
                e.fillStyle = chart.config.data.datasets[i].labelColor;
                e.strokeStyle = chart.config.data.datasets[i].labelColor;
            });
        }
    }
});

All 3 comments

My solutuon:

With the dataset I and extra color code called'labelColor', and set it with this:

Chart.plugins.register({
    beforeDraw: function (chart) {
        if (chart.config.data.datasets[0].labelColor) {
            let legends = chart.legend.legendItems;
            legends.forEach(function (e, i) {
                e.fillStyle = chart.config.data.datasets[i].labelColor;
                e.strokeStyle = chart.config.data.datasets[i].labelColor;
            });
        }
    }
});

Thanks @Hedva, your code helped me totally.

My version:

beforeDraw: function (chart) {
  chart.config.data.datasets.forEach((dataset,i)=>{
    if(dataset.legendBackgroundColor){
      chart.legend.legendItems[i].fillStyle = dataset.legendBackgroundColor;
      chart.legend.legendItems[i].strokeStyle = dataset.legendBorderColor ? dataset.legendBorderColor : dataset.legendBackgroundColor;
    }
  });
}

Thanks.

Plugins saved my day! Thank you@hedva

Was this page helpful?
0 / 5 - 0 ratings