I'm using an amCharts v4 Pie chart and currently I have this tooltip that appears when hovering on the slices:
series.slices.template.tooltipText = "{category}: {value.percent.formatNumber('#.')}% ({value} hours)
However, I would like to have the "hours" pluralized correctly, i.e. when {value}
equals 1, I would like to have the text hour
instead of hours
.
Is something like this possible? I've found the Adapters, but I don't think they will be usable here because I'm using a special format with category, percentage and the text.
Adapters are the perfect use case for this. You can look at the dataItem associated with the tooltip and use that logic to determine whether return the pluralized version of your tooltip or use the default one, for example:
pieSeries.slices.template.adapter.add('tooltipText', function(tooltipText, target) {
if (target.dataItem && target.dataItem.value == 1) {
return tooltipText.replace('hours', 'hour')
}
else {
return tooltipText;
}
});
Demo below:
var chart = am4core.create("chartdiv", am4charts.PieChart);
chart.data = [{
"country": "Lithuania",
"hours": 1
}, {
"country": "Czechia",
"hours": 2
}, {
"country": "Ireland",
"hours": 3
}, {
"country": "Germany",
"hours": 1
}, {
"country": "Australia",
"hours": 1
}, {
"country": "Austria",
"hours": 1
}];
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "hours";
pieSeries.dataFields.category = "country";
pieSeries.slices.template.tooltipText = "{category}: {value.percent.numberFormatter('#.')}% ({value} hours)";
pieSeries.slices.template.adapter.add('tooltipText', function(tooltipText, target) {
if (target.dataItem && target.dataItem.value == 1) {
return tooltipText.replace('hours', 'hour')
}
else {
return tooltipText;
}
});
chart.legend = new am4charts.Legend();
#chartdiv {
width: 100%;
height: 400px;
}
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv"></div>