Проценты не отображаются, хотя я вычисляю их в JavaScript с помощью Chart.js и диаграмма отображается правильно.Общий процент составляет более 100%.
Вот разбивка того, что я сделал на данный момент:
PHP-часть: я использую PHP для анализа CSV-файл и подсчитать количество вхождений различных эмоции. Затем я передаю метки эмоций и их количество в JavaScript.
Часть Chart.js: я использую плагин меток данных Chart.js, чтобы попытаться отобразить проценты на диаграмме.
Вот мой PHP-код для чтения CSV и подсчета возникновения каждой эмоции:
Код: Выделить всё
Код: Выделить всё
const doughnutCtx = document.getElementById('emotionDoughnutChart').getContext('2d');
const emotionLabels = ;
const emotionCounts = ;
// 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 } }
}
});
Подробнее здесь: https://stackoverflow.com/questions/792 ... g-chart-js