Chartjs-Chart.js: Legends for two datasets in Doughnut Chart

0👍

enter image description here

If you use Chart.js version 3.x or higher.

Fill the legend background color in the first dataset.

You set null or ‘ ‘ for ‘data’, ‘backgroundColor’ fields respectively like below example.

var ctx = document.getElementById('myChart');
var data = {
  labels: ['Red', 'Blue', 'Yellow', 'Pink', 'Lightgreen', 'Tomato', 'Orange'],
  datasets: [
    {
      data: [300, 50, 100, null, null, null, null, null],
      backgroundColor: ['red', 'blue', 'yellow', 'pink', 'lightgreen', 'tomato', 'orange'],
    },
    {
      data: [null, null, null, 345.56, 56.47, 987.12, 78.01],
      backgroundColor: [null, null, null, 'pink', 'lightgreen', 'tomato', 'orange'],
    },
  ],
};

var options = {
  responsive: true,
  plugins: {
    legend: {
      onClick: this.handleClick,
      onHover: this.handleHover,
      onLeave: this.handleLeave,
    },
  },
};

var myDoughnutChart = new Chart(ctx, {
  type: 'doughnut',
  data,
  options,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Example: Legends for Multiple Chart Different Colors

enter image description here

var ctx = document.getElementById('myChart');
var data = {
  labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Tomato', 'Pink', 'Gray'],
  datasets: [
    {
      data: [20, 40, 50, null, null, null, null, null],
      backgroundColor: ['#ff6384', '#ff9f40', '#ffcd56', '#4bc0c0', '#36a2eb', 'tomato', 'pink', 'gray'],
    },
    {
      data: [null, null, null, 60, 10, 20],
      backgroundColor: [null, null, null, '#4bc0c0', '#36a2eb', 'tomato'],
    },
    {
      data: [null, null, null, null, null, null, 20, 40],
      backgroundColor: [null, null, null, null, null, null, 'pink', 'gray'],
    },
  ],
};

var options = {
  responsive: true,
  plugins: {
    legend: {
      onClick: this.handleClick,
      onHover: this.handleHover,
      onLeave: this.handleLeave,
    },
  },
};

var myDoughnutChart = new Chart(ctx, {
  type: 'doughnut',
  data,
  options,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Leave a comment