[英]Create grouped-bar using chart.js, php and mysql
I have table biggest_user in mysql like this:我在 mysql 中有一个表 big_user,如下所示:
and i want to create grouped-bar using chart.js.我想使用chart.js创建分组栏。
I already create code like this:我已经创建了这样的代码:
<html>
<head>
<script src="Chart.min.js"></script>
</head>
<body>
<center>
<?php
include 'conn.php';
$sql = "Select date, user, sum(total) as total from user_biggest group by date,user";
# $sql = "SELECT difference, date FROM `biggest_user`";
$date = $conn->query($sql);
$user = $conn->query($sql);
$total = $conn->query($sql);
?>
<canvas id="bar-chart-grouped" width="1000" height="250"></canvas>
<script>
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: [<?php while($a = mysqli_fetch_array($date)) { echo '"' . $a['date'] . '",'; } ?>],
datasets: [
{
label: "Total",
backgroundColor: "#3e95cd",
data: [<?php while($b = mysqli_fetch_array($total)) { echo $b['total'] . ', '; } ?>]
},
{
label: "User",
backgroundColor: "#8e5ea2",
data: [<?php while($c = mysqli_fetch_array($user)) { echo $b['user'] . ', '; } ?>]
}
]
},
options: {
title: {
display: true,
text: 'Biggest User (Megabytes)'
}
}
});
</script>
but the result chart is like this:但结果图表是这样的:
I think it's not grouped-bar chart.我认为它不是分组条形图。 but i don't know what's wrong in my code.
但我不知道我的代码有什么问题。
Unfortunately I don't know much about php
.不幸的是,我对
php
了解不多。 Therefore I can only partially answer your question.所以我只能部分回答你的问题。
data.labels
should contain an entry for each day. data.labels
应该包含每天的条目。 What you further need is one dataset
for each user and that's it.您进一步需要的是每个用户的一个
dataset
,仅此而已。
Please take a look at below code snippet and see how it could work.请看看下面的代码片段,看看它是如何工作的。
new Chart("chart", { type: 'bar', data: { labels: ["01-Sep-20", "02-Sep-20", "03-Sep-20"], datasets: [{ label: "cs", backgroundColor: "red", data: [229, 200, 198] }, { label: "finance", backgroundColor: "green", data: [162, 150, 178] }, { label: "credit", backgroundColor: "blue", data: [89, 156, 90] }, { label: "it", backgroundColor: "orange", data: [89, 55, 112] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="chart" height="90"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.