|
1 | 1 | let barConfig;
|
2 | 2 | let pieConfig;
|
3 | 3 | let myChart;
|
4 |
| -let totalSum; |
5 | 4 | const ctx = document.getElementById("myChart");
|
6 | 5 |
|
7 | 6 | function togglePieChart() {
|
@@ -57,9 +56,6 @@ const loadData = (data) => {
|
57 | 56 | dfw,
|
58 | 57 | ];
|
59 | 58 |
|
60 |
| - // Calculate total number of students |
61 |
| - totalSum = grades_data.reduce((total, num) => total + num, 0); |
62 |
| - |
63 | 59 | // Create default pie chart
|
64 | 60 | /* eslint-enable camelcase */
|
65 | 61 | createChart(grades_data);
|
@@ -241,33 +237,46 @@ const createChart = (gradesData) => {
|
241 | 237 | },
|
242 | 238 | },
|
243 | 239 | };
|
| 240 | + // eslint-disable-next-line no-new,no-undef |
| 241 | + Chart.register(ChartDataLabels); |
244 | 242 |
|
245 |
| - // Generate configuration for Pie Chart |
246 | 243 | pieConfig = {
|
247 | 244 | type: "doughnut",
|
248 | 245 | data: chartData,
|
249 | 246 | options: {
|
250 | 247 | maintainAspectRatio: false,
|
251 |
| - tooltips: { |
252 |
| - callbacks: { |
253 |
| - label: function (tooltipItem, data) { |
254 |
| - const dataset = data.datasets[0]; |
255 |
| - const percent = Math.round( |
256 |
| - (dataset.data[tooltipItem.index] / totalSum) * 100, |
257 |
| - ); |
258 |
| - let label = data.labels[tooltipItem.index]; |
259 |
| - if (tooltipItem.index === 9) { |
260 |
| - label = "D/F/Withdraw"; |
261 |
| - } |
262 |
| - return label + ": " + percent + "%"; |
263 |
| - }, |
264 |
| - }, |
265 |
| - displayColors: false, |
266 |
| - }, |
267 | 248 | plugins: {
|
268 | 249 | legend: {
|
269 | 250 | display: false,
|
270 | 251 | },
|
| 252 | + datalabels: { |
| 253 | + color: "#fff", |
| 254 | + formatter: (value, context) => { |
| 255 | + const dataset = context.chart.data.datasets[0]; |
| 256 | + const total = dataset.data.reduce((acc, num) => acc + num, 0); |
| 257 | + const percentage = (value / total) * 100; |
| 258 | + return percentage > 5 |
| 259 | + ? context.chart.data.labels[context.dataIndex] |
| 260 | + : ""; |
| 261 | + }, |
| 262 | + font: { |
| 263 | + size: 14, |
| 264 | + }, |
| 265 | + anchor: "center", |
| 266 | + align: "center", |
| 267 | + }, |
| 268 | + tooltip: { |
| 269 | + callbacks: { |
| 270 | + label: function (tooltipItem) { |
| 271 | + const dataset = tooltipItem.dataset; |
| 272 | + const total = dataset.data.reduce((acc, num) => acc + num, 0); |
| 273 | + const value = dataset.data[tooltipItem.dataIndex]; |
| 274 | + const percent = ((value / total) * 100).toFixed(1); |
| 275 | + return `${value} (${percent}%)`; |
| 276 | + }, |
| 277 | + }, |
| 278 | + displayColors: false, |
| 279 | + }, |
271 | 280 | labels: {
|
272 | 281 | // render 'label', 'value', 'percentage', 'image' or custom function, default is 'percentage'
|
273 | 282 | render: "label",
|
|
0 commit comments