1

I'm a bit new to Chart.js. Is there a way to create a legend for each element in the dataset? What I'm trying to get is it to generate one legend for "Votes" and one for "2nd Votes".


var mybarChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Votes', '2nd Votes'],
    datasets: [{
      label: '# of Votes',
      backgroundColor: "#000080",
      data: [80, 50]
    }]
  },

  options: {
    legend: {
      display: true,
      position: 'bottom',
      labels: {
        fontColor: "#000080",
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});```
Shaunak
  • 17,377
  • 5
  • 53
  • 84

1 Answers1

0

Here's one way to do it. Simply split your data points into individual objects in the data array.

(run the snippet in full screen)

const config = {
  type: 'bar',
  data: {
    labels: ['Votes'],
    datasets: [{
      label: '# of Votes',
      backgroundColor: "#000080",
      data: [80]
    },
    {
      label: ' 2nd Votes',
      backgroundColor: "#800080",
      data: [50]
    }]
  },

  options: {
    legend: {
      display: true,
      position: 'bottom',
      labels: {
        fontColor: "#000080",
      }
    },
    scales: {
      
    }
  }
};

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx,config)
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Shaunak
  • 17,377
  • 5
  • 53
  • 84