This short tutorial will show how to pre-hide individual slices of a pie chart, in this case ones that have zero value.
Hiding a slice
To a hide a slice on a pie series (or any other percent series for that matter), we need to call the hide()
method of its data item.
For example, the following code will hide the second slice in series:
series.dataItems[1].hide(0);
series.dataItems[1].hide(0);
NOTEThe number in parameter of hide()
means duration (in milliseconds) the hiding animation will take. Use zero for immediate hide.
Waiting for data
Please note, that data items for the series might not be ready immediately.
To work around that we can use series' datavalidated
event, which kicks in when data is parsed and all data items are created.
series.events.on("datavalidated", function() { series.dataItems[1].hide(0) });
series.events.on("datavalidated", function() { series.dataItems[1].hide(0) });
Filtering slices to hide
Now, one thing left is to filter out actual slices (data items) to hide:
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.get("value") == 0) { dataItem.hide(); } }) });
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.get("value") == 0) { dataItem.hide(); } }) });
You could use any logic to filtering slices, too.
The following code will check for hidden
value in source data:
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.dataContext.hidden) { dataItem.hide(); } }) });
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.dataContext.hidden) { dataItem.hide(); } }) });
Removing filtered slices from legend
We can use datavalidated
to selectively populate legend data, too:
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.get("value") == 0) { dataItem.hide(); } else { legend.data.push(dataItem); } }) });
series.events.on("datavalidated", function() { am5.array.each(series.dataItems, function(dataItem) { if (dataItem.get("value") == 0) { dataItem.hide(); } else { legend.data.push(dataItem); } }) });
Example
See the Pen Pre-hiding slices with zero values by amCharts team (@amcharts) on CodePen.