<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content="
width
=
device
-width,
initial-scale
=
1
.0">
<
title
>Pie Chart Example</
title
>
<
script
src
=
</
script
>
<
style
>
div {
height: 50vh;
width: 50vw;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksForGeeks | Pie Chart</
h1
>
<
div
>
<
canvas
id
=
"pieChart"
width
=
"400"
height
=
"400"
>
</
canvas
>
</
div
>
<
script
>
// Get the 2D rendering context of the canvas
let ctx = document.getElementById('pieChart')
.getContext('2d');
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 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 // Border width for each segment
}]
}
// Create a new Pie Chart
let pieChart = new Chart(ctx, {
// Specify the chart type
type: 'pie',
// Provide data for the chart
data: dataValue,
// Additional options for the chart
options: {
responsive: true, // It make the chart responsive
// This plugin will display Title of chart
plugins: {
title: {
display: true,
text: 'Number of Students Enrolled Course'
}
},
// Event handler for a click on a chart element
onClick: function (event, elements) {
const clickedElement = elements[0];
const datasetIndex = clickedElement.index;
const label = dataValue.labels[datasetIndex];
const labelValue = dataValue.datasets[0].data[datasetIndex];
// Show an alert with information about the clicked segment
alert(`Clicked on: ${label} and it's value is ${labelValue}`);
}
}
});
</
script
>
</
body
>
</
html
>