How to show values in the slices

Currently, there is no native Chart.js way to show values or percentages in a pie chart without tooltips. But you can achieve this using a plugin or extension. In the following example, we will use a very simple library called Chart.Piecelabel.js. You can download it from github.com/emn178/Chart.PieceLabel.js and include it your page using a script tag:

<script src="../JavaScript/Chart.PieceLabel.js"></script>

That's it! Now you can add the pieceLabel property to the options object, and configure labels for the slices. You can display absolute values or percentages, place the labels inside, at the border or outside the slices, draw the text on the arc and configure several font attributes. The following is a selection of these properties (you can check the library's documentation for more properties):

Property

Value

Description

render

'percentage' (default) or 'value'

Displays the percentage or the value of the slice.

precision

Number

The precision (number of digits after the decimal point) for percentages (does not work with other values).

fontSize, fontColor, fontSize, and fontFamily

CSS property value strings

Changes font attributes for the label.

textShadow

true or false

Applies a shadow to the label (the shadow attributes, such as offset and color, can also be configured with additional properties).

position

'default', 'border' or 'outside'

Places the label in the different positions.

arc

true or false

Draws the text aligned with the arc. Works better when the position is 'outside'.

Some configuration options for the Chart.PieceLabel.js plugin

To include labels in the pie chart you created in the previous example, add the following property to the options object of your chart (see Pie/pie-3-plugin.html):

options:{
pieceLabel: {
fontColor: '#000',
render: 'value',
textShadow: true,
position: 'border'
},

Run the script and you have labels containing the value represented by each slice, as shown in the following chart:

A simple pie chart using the Chart.PieceLabel.js extension to display labels on each slice (code: Pie/pie-3-plugin.html)

If you want even more customization, you can try other plugins such as ChartJS-Datalabels and ChartJS-Outlabels, which support sophisticated label placement options. These two plugins will be explored in Chapter 6, Configuring Styles and Interactivity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset