[Chartjs]-Chart.js, Can you override the legend label box color?

2đź‘Ť

âś…

Github related issue: https://github.com/chartjs/Chart.js/issues/2651

You should use generateLabels function.
https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration

// Fill style of the legend box
fillStyle: Color,

Inside generateLabels

/* change legend of label index 0 [first object] */
labels[0].fillStyle  = "rgba(133, 4, 12, 0.7)";`

Code example:

var customLegendColor = 'rgba(0, 51, 78, 0.3)';

var data = {
  labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
  datasets: [
    {
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
      data: [2478,5267,734,784,433]
    }
  ]
};

var options = {
  title: {
    text: 'Custom legend example',
    position: 'bottom'
  },
  legend: {
    display: true,
    labels: {
      fontColor: 'rgb(255, 99, 132)',
      fontSize: 22,
      generateLabels: function(chart) {
        labels = Chart.defaults.global.legend.labels.generateLabels(chart);
        for (var key in labels) {
          labels[key].text = "Hello World";
          labels[key].fillStyle  = "rgba(133, 4, 12, 0.7)";
          labels[key].strokeStyle = "rgba(33, 44, 22, 0.7)"; 
        }
        return labels;
      }
    }
  },
  scales: {
    xAxes: [{
    }],
    yAxes: [{
    }]
  }
};

var chart = new Chart(document.getElementById('chart'), {
  type: 'bar',
  data: data,
  options: options
});
<canvas id="chart" height="250px"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

List of legends:

Use data objects
https://codepen.io/jordanwillis/pen/xqrjGp?editors=1010

 datasets: [{
      label: 'one',
      backgroundColor: "#000080",
      data: [80]
    }, {
      label: 'two',
      backgroundColor: "#add8e6",
      data: [45]
    }]

UI

In general, this is a bad UI approach to change the color/text legend to “any color/text” (The color and text should match the bar color & text).

Leave a comment