Chart.js is an open-source free JavaScript library that is used to visualize data-informed charts. Doughnut charts are used to visualize data in a circular format. It makes it easy to understand the distribution of a dataset. In this article, we will learn about how to display custom data by tooltip in a doughnut chart with an example.
Chart.js CDN link:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Using the tooltip object callback for label
Tooltips in Chart.js are small pop-ups that appear when you hover over chart elements, that are used to display some additional information. You can implement a custom tooltip by using a custom tooltip callback function inside the plugins object. This callback function allows you to return custom data when the user hovers over the chart element.
Syntax:
options: {
// Object that allows customization of tooltips.
plugins: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
// Custom logic to generate tooltip content
return 'Custom Tooltip Content';
}
}
}
}
Example: In this example, we are displaying custom data by using tooltip in doughnut chart.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >
Doughnut Chart Custom
Tooltip Example
</ title >
<!-- Include Chart.js library -->
< script src =
</ script >
< style >
div {
height: 50vh;
width: 50vw;
}
</ style >
</ head >
< body >
< h1 >
GeeksForGeeks | Custom Tooltip
Doughnut Chart
</ h1 >
< div >
<!-- Create a canvas element
to render the chart -->
< canvas id = "DoughnutChart"
width = "400"
height = "400" >
</ canvas >
</ div >
< script >
// Get the canvas element and
// create the doughnut chart
let ctx = document.
getElementById('DoughnutChart').
getContext('2d');
// Data for Doughnut Chart
let dataValue = {
// Labels for each
// segment of the pie
labels: ['JavaScript',
'Python',
'Java',
'C++',
'PHP'],
// Datasets for the chart
datasets: [{
data: [40, 35, 25, 17, 18],
// Data points color
// for each segment
backgroundColor:
['rgba(255, 99, 132, 0.8)',
'rgba(75, 192, 192, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 205, 86, 0.8)',
'rgba(153, 102, 255, 0.8)'],
borderWidth: 2
}]
}
// Create Doughnut Chart
let myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: dataValue,
// Chart configuration options
options: {
plugins: {
// Title configuration
title: {
display: true,
text:
'Number of Students Enrolled in Each Course'
},
// Tooltip customization
tooltip: {
callbacks: {
// Custom label for tooltip
label: function (tooltipItem) {
let label = tooltipItem.label;
let value = tooltipItem.
formattedValue;
return `
No of students enrolled
in ${label} is ${value}`
}
}
}
}
}
});
</ script >
</ body >
</ html >
|
Output: