I'm labelling sectors of a pie-chart in amCharts5 with the 'category' value. I want to change the label text to 'Unknown' on any sector which has an empty category value.
I've written an adapter but I get the following error:
"Uncaught TypeError: Cannot read properties of undefined (reading 'get')"
It looks like dataItem is not being instantiated. I don't understand why not.
How might I check for empty labels and replace them with 'Unknown'?
// Create pie-chart series
var series = chart.series.push(am5percent.PieSeries.new(root, {
valueField: "eventCount",
categoryField: "category"
}));
// Add adapter to change label on empty sectors to 'Unknown'.
series.labels.template.adapters.add("text", function(text, target) {
return target.dataItem.get("category").length > 0 ? text : 'Unknown';
});
You have to check if
dataItem
is defined, then access the category throughdataContext
.Your code should look like this:
Here is a full example:
Warning: my code above uses optional chaining (?.) for which you may need a polyfill. If you do not want that, you can do this instead: