[Chartjs]-What happened to generateLegend() in chartjs 3.0?

3👍

Yes, there’s a pretty simple way to add a custom legend to chartJS 3.5 by using plugins.

Here’s an example of how it could work:

  1. Create your DOM structure to support the new legend and chartjs chart.
<div id="legend-id"></div>
<canvas id="chart-id"></canvas>
  1. Setup your chart with some default data and options to hide the current legend.
const data = {
  labels: [
    'Red',
    'Blue',
    'Yellow'
  ],
  datasets: [{
    label: 'My First Dataset',
    data: [300, 50, 100],
    backgroundColor: [
      'rgb(255, 99, 132)',
      'rgb(54, 162, 235)',
      'rgb(255, 205, 86)'
    ],
    hoverOffset: 4
  }]
};

const options = {
  plugins: {
    legend: {
        display: false
    }
  }
};

  1. Attach the chart (with the custom legend) to your DOM structure.
const context = document.querySelector("#chart-id");
const chart = new Chart(context, {
  type: "doughnut",
  data,
  options,
  plugins: [{
    beforeInit: function(chart, args, options) {
      // Make sure we're applying the legend to the right chart
      if (chart.canvas.id === "chart-id") {
        const ul = document.createElement('ul');
        chart.data.labels.forEach((label, i) => {
          ul.innerHTML += `
            <li>
              <span style="background-color: ${ chart.data.datasets[0].backgroundColor[i] }">
                ${ chart.data.datasets[0].data[i] }
              </span>
              ${ label }
            </li>
          `;
        });

        return document.getElementById("js-legend").appendChild(ul);
      }

      return;
    }
  }]  
});

Additionally here’s a working jsfiddle with this custom legend!

Leave a comment