我有一个饼图,它引用数组中的值。
我想以百分比显示这些数组值。我该怎么做?
我用来生成此饼图的插件是chart.js
Javascript供参考:
success : function (data){
console.log(data);
var categoryname = ["Drain", "Building", "Pest", "Broken Utilities",
"Littering", "Leakage", "Lighting"];
var category = [];
var amount = [];
for (var i in data) {
category.push(categoryname[data[i].Category]);
amount.push (data[i].CaseNum);
}
var config = {
type: 'pie',
data: {
datasets: [{
data: amount,
backgroundColor: [
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)"
],
label: 'Dataset 1'
}],
labels: category
},
options: {
responsive: true
}
};
var ctx = $("#mycanvas");
var graph = new Chart(ctx, config);
}
Php供参考:
$query = "SELECT categoryID as 'Category', COUNT(Case.categoryID) as 'CaseNum'
FROM `Case` WHERE CaseTime BETWEEN DATE_SUB(now(), INTERVAL 6 MONTH) AND
now() GROUP BY categoryID ORDER BY categoryID";
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$conn->close();
print json_encode($data);
答案 0 :(得分:0)
试试这个
success : function (data){
console.log(data);
var integerAmount = [];
for (var i in data) {
integerAmount.push(data[i].CaseNum);
}
var sum = integerAmount.reduce((a, b) => a + b, 0);
var categoryname = ["Drain", "Building", "Pest", "Broken Utilities", "Littering", "Leakage", "Lighting"];
var category = [];
var amount = [];
for (var i in data) {
category.push(categoryname[data[i].Category]);
amount.push (integerAmount[i]/sum*100+'%');
}
// rest of the script
}
我们的想法是首先从data
对象存储Integers值。然后总和总值。最后,我们推送实际百分比值并将%
添加到饼图的amount
数据中。