I’m working on a project where I need to generate a Doughnut chart displaying the percentage distribution of different emotions based on data stored in a CSV file. I’m using PHP to parse the CSV and Chart.js to create the chart. However, I’m currently having two main issues:
The percentages are not showing up, even though I’m calculating them in JavaScript using Chart.js and the chart is properly rendered.
The total percentage adds up to over 100%.
Here’s a breakdown of what I’ve done so far:
PHP part: I’m using PHP to parse the CSV file and count the occurrences of different emotions. I then pass the emotion labels and their counts to JavaScript.
Chart.js part: I’m using the Chart.js datalabels plugin to try to show percentages on the chart.
Here’s my PHP code to read the CSV and count the occurrences of each emotion:
<?php
$data = array_map('str_getcsv', file('data_export.csv'));
array_shift($data); // Skip header if present
$emotion_map = [
'Excitement' => 1,
'Inspiration' => 2,
'Joy' => 3,
'Curiosity' => 4,
'Pride' => 5,
'Hope' => 6,
'Stress' => 7,
'Panic' => 8,
'Relief' => 9,
'Confusion' => 10,
'Boredom' => 11,
'Disappointment' => 12,
];
$emotion_count = array_fill_keys(array_keys($emotion_map), 0);
foreach ($data as $row) {
$emotion = trim($row[0]);
if (isset($emotion_map[$emotion])) {
$emotion_count[$emotion]++;
}
}
?>
And here’s my JavaScript code for generating the Doughnut chart:
const doughnutCtx = document.getElementById('emotionDoughnutChart').getContext('2d');
const emotionLabels = <?php echo json_encode(array_keys($emotion_count)); ?>;
const emotionCounts = <?php echo json_encode(array_values($emotion_count)); ?>;
// Calculate the total count
const totalCount = emotionCounts.reduce((sum, count) => sum + count, 0);
const doughnutChart = new Chart(doughnutCtx, {
type: 'doughnut',
data: {
labels: emotionLabels,
datasets: [{
label: 'Emotion Distribution',
data: emotionCounts,
backgroundColor: [
'#1E90FF', '#FF7F50', '#FFE4B5', '#8BC34A', '#32CD32', '#4CAF50', '#D3D3D3',
'#DC143B', '#8BC34A', '#7FFFD4', '#DDA0DD', '#D8BFD8'
],
hoverOffset: 5
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'top',
labels: { font: { size: 10 } }
},
title: { display: true, text: 'Emotion Distribution' },
datalabels: {
color: 'white',
formatter: function(value, context) {
let percentage = (value / totalCount * 100).toFixed(2);
return `${percentage}%`; // Display percentage
},
font: { weight: 'bold', size: 14 }
}
},
layout: { padding: { top: 10, bottom: 10 } }
}
});
I have tried sing the chartjs-plugin-datalabels plugin to display the percentage but no luck .