6

I am using ng2 doughnut chart to display some items, Its all working fine as per the doughnut chart documentation but the thing i need to change is, the display of label of each slices comes only on hover but the thing i need is it should be in default in each slices.

Dashboard.component.html:

<canvas #mycanvas baseChart
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [chartType]="doughnutChartType"
    [colors]="colors"
    [options]="options"
    (chartHover)="chartHovered($event)"
    (chartClick)="chartClicked($event)">
</canvas>

Dashboard.component.ts:

public doughnutChartLabels:string[] = ['Running', 'Stop', 'Idle'];
public doughnutChartData:number[] = [1, 4, 5];
public doughnutChartType:string = 'doughnut';
public colors: any[] = [{ backgroundColor: ["#008000", "#FF0000", "#FFA500"] }];

The thing i am in the need is exactly as like in the image,

enter image description here

The labels should be in default in each slices and the thing needs to be achieved only by using pure typescript and no javascript. Kindly help me to achieve the desired result.

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
  • Refer to the chart.js documentation [Legend Config](http://www.chartjs.org/docs/latest/configuration/legend.html#example), you can use the input `[options]="options"` to pass the same options of the link above – JoxieMedina Oct 10 '17 at 06:47

2 Answers2

11

You can achieve that by using a Chart.js plugin called - Chart.PieceLabel.js.

first.. install it via npm :

npm install chart.piecelabel.js --save

then.. import it in your dashboard component :

import 'chart.piecelabel.js';

and finally.. set the following option in your chart­'s options config :

pieceLabel: {
   render: 'label'
}

note: this is the minimum option needs to be set to display the labels, and you can find more options here.

see - working example

ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110
1

'chartjs-plugin-labels' is the most popular display plugin. I just tried it. It works!

npm install chartjs-plugin-labels --save

In the desired angular 2+ component, add the following:

import 'chartjs-plugin-labels';

No need to import any module.

Here is the npm information:
https://www.npmjs.com/package/chartjs-plugin-labels

Site:
https://chartjs-plugin-datalabels.netlify.com/

Demo:
https://emn178.github.io/chartjs-plugin-labels/samples/demo/

package.json : combination which worked:

"chart.js": "^2.8.0",
"chartjs-plugin-labels": "^1.1.0",
jkdev
  • 11,360
  • 15
  • 54
  • 77
Anish Kutti
  • 337
  • 2
  • 7