Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help:
Chart.pluginService.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
https://jsfiddle.net/suhaibjanjua/qz3es03j/
I'm currently using Angular 5 and I'm unsure how to incorporate the above code into my component.ts file. Additionally, I would like to add a small black border to each tooltip. I know how to achieve this in CSS, but not sure how to implement it in the chart tooltips.
This is what my current component.ts looks like:
doughnutChartData: any[] = [0,18,26,16, 40];
doughnutChartLabels: any[] = ['NA', 'NE', 'NO', 'C', 'S'];
doughnutChartOptions: any = {
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 80,
tooltips: {
enabled: true,
backgroundColor: 'white',
titleFontColor: 'black',
bodyFontColor: 'black',
xPadding: 20,
yPadding: 20,
displayColors: false,
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
var total = 0;
for (var i in allData) {
total += allData[i];
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipPercentage + '%';
}
}
}
};
doughnutChartColors: any[] = [{
borderWidth: 3,
backgroundColor: ['#ffffff', '#e827d3', 'black', 'rgb(104, 104, 104)', 'gray']
}];
Here's the corresponding HTML:
<mat-card class="charts-npls first-chart">
<canvas baseChart
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[options]="doughnutChartOptions"
[colors]="doughnutChartColors"
[legend]="false"
chartType="doughnut">
</canvas>
</mat-card>