Search code examples
javascriptchart.js

chart js how to fill legend box with colour


I'm using Chart.js for line charts and I have the legend as below. Chart Legend

The problem is that the legend only has an outline color, I want the legend box to have the whole thing colored. I haven't found anything in the documentation to see why mine only has the border. I'm at a bit of a loss, here's an example of my setup:

var LinuxDistributionsCombined = document.getElementById('LinuxDistributionsCombined');
var myChart = new Chart.Line(LinuxDistributionsCombined, {
  type: 'line',
  data: {
    labels: ['Jul-2016', 'Sep-2016', 'Oct-2016', 'Dec-2016', 'Jan-2017', 'Feb-2017', 'Mar-2017', 'Apr-2017', 'May-2017', 'Jun-2017', 'Jul-2017', 'Aug-2017', 'Sep-2017', 'Oct-2017'],
    datasets: [{
      label: 'Ubuntu-based',
      fill: true,
      data: [0, 0, 0, 0, 51.37, 51.04, 50.64, 50.29, 49.6, 48.32, 47.95, 47.03, 46.42, 46.21],
      borderColor: '#a6cee3',
      borderWidth: 1
    }, {
      label: 'Arch-based',
      fill: true,
      data: [0, 0, 0, 0, 28.52, 28.53, 28.75, 29.02, 29.16, 30.42, 30.65, 31.29, 31.53, 31.93],
      borderColor: '#1f78b4',
      borderWidth: 1
    }, {
      label: 'Solus',
      fill: true,
      data: [0, 0, 0, 0, 0.42, 0.45, 0.61, 0.64, 0.92, 1.12, 1.08, 1.21, 1.23, 1.46],
      borderColor: '#6a3d9a',
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      display: true
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        },
        scaleLabel: {
          display: true,
          labelString: 'Percentage of users'
        }
      }]
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
          var label = data.datasets[tooltipItem.datasetIndex].label;
          return label + ' ' + value + '%';
        }
      },
    },
  }
});

Solution

  • You have to set the backgroundColor property for each of your datasets as well, as that is correspondent to legend box­'s fill color.

    ...
    datasets: [{
       label: 'Ubuntu-based',
       fill: true,
       data: [0, 0, 0, 0, 51.37, 51.04, 50.64, 50.29, 49.6, 48.32, 47.95, 47.03, 46.42, 46.21],
       backgroundColor: '#a6cee3',
       borderColor: '#a6cee3',
       borderWidth: 1
    }, {
       label: 'Arch-based',
       fill: true,
       data: [0, 0, 0, 0, 28.52, 28.53, 28.75, 29.02, 29.16, 30.42, 30.65, 31.29, 31.53, 31.93],
       backgroundColor: '#1f78b4',
       borderColor: '#1f78b4',
       borderWidth: 1
    }, {
       label: 'Solus',
       fill: true,
       data: [0, 0, 0, 0, 0.42, 0.45, 0.61, 0.64, 0.92, 1.12, 1.08, 1.21, 1.23, 1.46],
       backgroundColor: '#6a3d9a',
       borderColor: '#6a3d9a',
       borderWidth: 1
    }]
    ...