Labels in the legend

My problem is similar to How to show bar labels in legend in Chart.js 2.1.6?

I want to have the same output as the pie chart, but I don't want to create multiple datasets. I managed to do it, but now I can't find how to do it.

Here's my sample code:

 var myChart = new Chart(ctx, {
    type: type_p,
    data: {
        labels: ['Lundi','Mardi'],
        datasets: [{
            data: [50,20],
            backgroundColor: color,
            borderColor: color,
            borderWidth: 1
        }]
    }

      

I want the same legend as a pie chart, but with a bar chart: pie chart

Is this the way to do it?

+3


source to share


1 answer


To do this, you will need to create custom labels (using a function) based on an array of your dataset. generateLabels()

labels

legend: {
   labels: {
      generateLabels: function(chart) {
         var labels = chart.data.labels;
         var dataset = chart.data.datasets[0];
         var legend = labels.map(function(label, index) {
            return {
               datasetIndex: 0,
               fillStyle: dataset.backgroundColor && dataset.backgroundColor[index],
               strokeStyle: dataset.borderColor && dataset.borderColor[index],
               lineWidth: dataset.borderWidth,
               text: label
            }
         });
         return legend;
      }
   }
}

      

add this to your chart options



ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var ctx = canvas.getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi'],
      datasets: [{
         data: [1, 2, 3, 4, 5],
         backgroundColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff'],
         borderColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff'],
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      },
      legend: {
         labels: {
            generateLabels: function(chart) {
               var labels = chart.data.labels;
               var dataset = chart.data.datasets[0];
               var legend = labels.map(function(label, index) {
                  return {
                     datasetIndex: 0,
                     fillStyle: dataset.backgroundColor && dataset.backgroundColor[index],
                     strokeStyle: dataset.borderColor && dataset.borderColor[index],
                     lineWidth: dataset.borderWidth,
                     text: label
                  }
               });
               return legend;
            }
         }
      }
   }
});
      

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
      

Run codeHide result


+3


source







All Articles