Skip to content

Legend and Pie/Sliced series

This tutorial will walk through configuration options for legend content on a pie or other percent chart.

To add a legend, we simply need to create an instance of a Legend class (which is a part of “index” package), push it to chart’s children (or any other place we want it to be), as well as set its data (in case of a percent chart, we will probably want to use series data items as legend items).

let legend = chart.children.push(am5.Legend.new(root, {}));
legend.data.setAll(series.dataItems);

What goes into legend labels on a percent chart is controlled by four of the series’ settings:

Setting key Default Comment
legendLabelText {category} Text for the legend item label.
legendValueText {valuePercentTotal.formatNumber('0.00p')} Text for the legend item value label.

To change contents of the legend, we simply need to set corresponding setting value:

let series = chart.series.push(
am5percent.PieSeries.new(root, {
name: "Series",
categoryField: "country",
valueField: "sales",
legendLabelText: "{category}",
legendValueText: "{value}"
})
);

Labels support data placeholders (references to data item settings in curly brackets) so the text will be populated with actual data and values.

Since each legend item is constructed out of the series data items, their data will be used to populate it, e.g. PieSeriesDataItem.

Besides regular text and data placeholders, labels support square bracket in-line formatting blocks. E.g.:

let series = chart.series.push(
am5percent.PieSeries.new(root, {
name: "Series",
categoryField: "country",
valueField: "sales",
legendLabelText: "[{fill}]{category}[/]",
legendValueText: "[bold {fill}]{value}[/]"
})
);

The above will use slice’s fill (color) for category and value, as well as make category names bold.

Open in CodePen