Chartjs-Customize Pie Chart Legend in chart.js

0๐Ÿ‘

I looked over the docs and saw the generateLabels option of option.legend.labels

here is the code:
I have documented the lines than need explaining.

Plunker: https://plnkr.co/edit/pslaed7IIUZzazpNEFZU?p=preview

@Component({
  selector: 'my-app',
  template: `
    <div style="display: block">
  <canvas baseChart
              [data]="data"
              [labels]="labels"
              [chartType]="type"
              [options]="opts"></canvas>
</div>
  `,
})
export class App {
  name:string;
  public labels:string[] = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
  public data:number[] = [350, 450, 100];
  public type:string = 'pie';
  opts = 
  {
    // new option - not in chartjs doc
    newLegendLabels: ['NEW: Download Sales', 'NEW: In-Store Sales', 'NEW: Mail-Order Sales'];
    legend:
    {
      labels:
      { 
        // provide a function for label generation
        // doc: http://www.chartjs.org/docs/#chart-configuration-legend-label-configuration
        generateLabels:
          function(chart){
            var newLabels = [];
            // call the default generateLabels
            Chart.defaults.doughnut.legend.labels.generateLabels(chart)
            // loop over the default ones and override the text
            .forEach((label,i) =>
            { 
              // override the text with new corresponding text from newLegendLabels
              label.text = chart.options.newLegendLabels[i];
              // push new label
              newLabels.push(label)
            });
            // return new labels
            return newLabels;
          }
      }

    }
  }
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

Leave a comment