0
votes

I'm using the ChartModule in PrimeNG, which uses Chart.js.

I have a pie chart that shows a few different types of data, but one of those types (deliveries) sometimes has multiple instances. For example, I might have 10 different deliveries, all of which will have it's own pie piece. Each of those are all the same color, because they are all deliveries. This results in my legend having 10 different labels, all of the same color, that say something like "Delivery to KFC on 5/1/2017", "Delivery to KFC on 5/8/2017", etc. I'd like the details to continue showing up as is when you hover over the pie chart for more details, however I'd like my legend to simply show "Delivery" once, so I don't have an enormous legend full of labels of the same color. How can I go about doing this?

For better visualization, here is an example pie chart:

enter image description here

When you hover over one of the two blue pie pieces, I want it to continue showing the extra details, however, I want the legend to have only one blue label that simply says "Delivery". How can I do this?

1
you're going to have to write a plugin for this.. it isn't available by default as the supplied label is used for both legend and tooltip. - Ahmed Musallam

1 Answers

0
votes

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}`
  }
}