我对Google图表有疑问,是否可以将饼图的颜色与mysql表中记录集的值相匹配
$fetchqry="SELECT
1219_set1.warna AS x,
round((Sum(cc)/1000),2) AS y,
kodewarna.nmwarna,
kodewarna.hexacolor
FROM
1219_set1
INNER JOIN kodewarna ON kodewarna.kdwarna = 1219_set1.warna
WHERE
1219_set1.thn = 2019 AND
1219_set1.bln = 11 AND
1219_set1.cabang = 'st'
GROUP BY
1219_set1.warna
";
那里有六色,还有Google图表
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(initChart);
$(window).on("throttledresize", function (event) {
initChart();
});
function initChart() {
var options = {
legend:'none',
width: '100%',
height: '100%',
pieSliceText: 'percentage',
colors: ['#0598d8', '#f97263'],
chartArea: {
left: "3%",
top: "3%",
height: "94%",
width: "94%"
}
};
var data = google.visualization.arrayToDataTable([
['Warna', 'Vol (L)'], <?php
$result=mysqli_query($con,$fetchqry);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "['".$row['x']."', ".$row['y']."],";
} ?> ]);
drawChart(data, options)
}
function drawChart(data, options) {
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, options);
}
colors
配置选项采用颜色数组数组中的每种颜色都将分配给图表中的一个切片
所以我们只需要加载colors数组,与数据表的顺序相同。
我们可以先声明数据行和颜色的数组来完成此操作
var rows = [['Warna', 'Vol (L)']];
var colors = [];
然后从sql结果中加载每个数组
<?php
$result=mysqli_query($con,$fetchqry);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "rows.push(['".$row['x']."', ".$row['y']."]);";
echo "colors.push('".$row['hexacolor']."');";
}
?>
在这里使用数据行数组...
var data = google.visualization.arrayToDataTable(rows);
以及选项中的颜色数组,这里...
var options = {
colors: colors,
请参见以下代码段...
google.charts.load('current', {
packages: ['corechart']
}).then(initChart);
$(window).on('throttledresize', initChart);
function initChart() {
var rows = [['Warna', 'Vol (L)']];
var colors = [];
<?php
$result=mysqli_query($con,$fetchqry);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "rows.push(['".$row['x']."', ".$row['y']."]);";
echo "colors.push('".$row['hexacolor']."');";
}
?>
var data = google.visualization.arrayToDataTable(rows);
var options = {
legend: 'none',
width: '100%',
height: '100%',
pieSliceText: 'percentage',
colors: colors,
chartArea: {
left: "3%",
top: "3%",
height: "94%",
width: "94%"
}
};
drawChart(data, options)
}
function drawChart(data, options) {
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, options);
}
NOTE
如果您使用jsapi
加载Google图表,该加载程序已过时,不应再使用。而是使用以下脚本文件...
<script src="https://www.gstatic.com/charts/loader.js"></script>
这只会更改load
语句,参见上面的代码段...