How to create a custom legend in angular -chart.js Pie Chart

I used angular -chart.js on my website to create a pie chart and I would like to customize the legend. By default, the legend displays the color and label. (As shown in the image below), I would like to add the value / data of this label, as shown in the chart tooltip.

enter image description here

This is my HTML code:

<canvas id="pie" class="chart chart-pie"
   chart-data="chartData" chart-labels="chartLabels" chart-options="chartOptions">
</canvas>

Based on the documentation of angular -chart.js, the legend is now a parameter to Chart.js, so the chart legend attribute has been removed.

This is why in my JS code I tried to add generateLabels, just in case, this is what I need to set up the legend:

$scope.chartOptions = { 
        legend: {
          display: true,
          labels: {
            generateLabels: function(chart){
              console.log(chart.config);
            }
          }
        }
      };

, , . , - . , generateLabels - , .

- , ?

!

+4
1

/ :

generateLabels: v1, , Legend Item Interface, . , - :

var theHelp = Chart.helpers;
// You need this for later

// Inside Options:
legend: {
display: true,    
// generateLabels changes from chart to chart,  check the source, 
// this one is from the doughnut :
// https://github.com/chartjs/Chart.js/blob/master/src/controllers/controller.doughnut.js#L42
labels: {
  generateLabels: function(chart) {
    var data = chart.data;
    if (data.labels.length && data.datasets.length) {
      return data.labels.map(function(label, i) {
        var meta = chart.getDatasetMeta(0);
        var ds = data.datasets[0];
        var arc = meta.data[i];
        var custom = arc && arc.custom || {};
        var getValueAtIndexOrDefault = theHelp.getValueAtIndexOrDefault;
        var arcOpts = chart.options.elements.arc;
        var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
        var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
        var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
          return {
          // And finally : 
          text: ds.data[i] + "% of the time " + label,
          fillStyle: fill,
          strokeStyle: stroke,
          lineWidth: bw,
          hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
          index: i
        };
      });
    }
    return [];
  }
}
}

: Chart.js pie Custom Legend

Codepen: Chart.js

, /, , ( )

- , :

myPieChart.generateLegend();

Html:

"<ul class='0-legend'><li><span style='background-color:black'>  </span>she returns it </li><li><span style='background-color:white'></span>she keeps it</li></ul>"

, , . Html, .

+8

Source: https://habr.com/ru/post/1658817/


All Articles