Chartjs-Chart.js custom legend colour based

0👍

You can’t. At least not with Chart.JS alone. You need to create a function to summarize the data.

Here is a that which loop into colors array. It will find all similar colors and group them together. The labels are also changed to "A & B & C".

var canvas = document.getElementById("pieChart");
var ctx = canvas.getContext('2d');

Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontSize = 16;
var theHelp = Chart.helpers;

var globals = {
  labels: ["test1 ", "test2", "test3"],
  colors: ['green', 'red', 'red'],
  data: [5, 95, 30],
}

function groupedData() {
  let obj = {
    labels: [],
    colors: [],
    data: []
  }

  for (let i = 0; i < globals.colors.length; i++) {
    const found = obj.colors.indexOf(globals.colors[i])
    if (found !== -1) {
      obj.labels[found] += " - " + globals.labels[i]
      obj.data[found] += globals.data[i]
      obj.colors[found] = globals.colors[i]
    } else {
      obj.labels.push(globals.labels[i])
      obj.colors.push(globals.colors[i])
      obj.data.push(globals.data[i])
    }
  }

  return obj
}


var data = {
  labels: groupedData().labels,
  datasets: [{
    fill: true,
    backgroundColor: groupedData().colors,
    data: groupedData().data,
  }]
};

var options = {
  rotation: -0.7 * Math.PI,
  legend: {
    display: true,
    labels: {
      generateLabels: function(chart) {
        var data = chart.data;
        if (data.labels.length && data.datasets.length) {
          return data.labels.map(function(label, i) {
            var meta = chart.getDatasetMeta(0);
            var ds = data.datasets[0];
            var arc = meta.data[i];
            var custom = arc && arc.custom || {};
            var getValueAtIndexOrDefault = theHelp.getValueAtIndexOrDefault;
            var arcOpts = chart.options.elements.arc;
            var fill = custom.backgroundColor ? custom.backgroundColor :
              getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
            var stroke = custom.borderColor ? custom.borderColor :
              getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
            var bw = custom.borderWidth ? custom.borderWidth :
              getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
            return {
              text: label,
              fillStyle: fill,
              strokeStyle: stroke,
              lineWidth: bw,
              hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
              index: i
            };
          });
        }
        return [];
      }
    }
  }
};

// Chart declaration:
var myPieChart = new Chart(ctx, {
  type: 'pie',
  data: data,
  options: options
});
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="./js/script.js"></script>
</head>

<div class="container">
  <br />
  <div class="row">
    <div class="col-md-1"></div>
    <div class="col-md-10">

      <canvas id="pieChart"></canvas>
    </div>
    <div class="col-md-1"></div>
  </div>
</div>

Leave a comment