Chartjs-Chart.js Barchart how to create legend item for bar?

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>

Leave a comment