根据mysql值更改谷歌饼图切片的颜色



我目前在一个页面上有两个使用MYSQL填充的图表,其中一个是条形图,另一个是饼图

我已经成功地基于mysql更改了条形图的颜色,但似乎无法使用相同的代码更改饼图的颜色。我得到的结果是,整个图表变成了最大切片的颜色。例如,对于下表中的数据,整个图表会变成红色,成为最大切片的

数据字符串如下所示:

|---------------------|------------------|
|      location       |      beacon      |
|---------------------|------------------|
|         RED         |         34       |
|---------------------|------------------|
|         Blue        |         34       |
|---------------------|------------------|
|         Green       |         34       |
|---------------------|------------------|
|         RED         |         34       |
|---------------------|------------------|
|        Yellow       |         34       |
|---------------------|------------------| 

因此,图表所需的结果将是4片红、蓝、绿、黄

我遇到的问题是,因为图表是由mysql填充的,我无法手动定义颜色,因为每次加载图表时,部分的显示方式可能会有所不同。

<script type="text/javascript">  
google.charts.load('current', {'packages':['corechart']});  
google.charts.setOnLoadCallback(drawChart);  
function drawChart()  
{  
var data = google.visualization.arrayToDataTable([  
['location', 'count'],  
<?php 
$connect = mysqli_connect("localhost", "user", "password", "test");  
if(isset($_POST['but_search'])){
$fromDate = $_POST['fromDate'];
$endDate = $_POST['endDate'];
if(!empty($fromDate) && !empty($endDate)){
$emp_query .= " and date_of_join 
between '".$fromDate."' and '".$endDate."' ";
}
}  
$query = "SELECT location,count(location) as customer_count FROM test.filter where date between '".$fromDate."' and '".$endDate."' group by location ";  
$result = mysqli_query($connect, $query); 
while($row = mysqli_fetch_array($result))  
{  
echo "['".$row["location"]."', ".$row["count"]."],"; 
}  
?>  
]); 
for (var i = 0; i < data.getNumberOfRows(); i++) {
var colors = [];
colors.push(data.getValue(i, 0));
var options = {  
title: 'Zone Statistics',  
is3D:false,  
pieHole: 0.4,  
colors: colors,
textStyle:{color: 'black'},
legend:{position: 'none'},
chartArea: {width: 550, height: 300},
legend: 'labeled',
pieSliceText: 'none',
backgroundColor: '#E4E4E4',
};  
var chart = new google.visualization.PieChart(document.getElementById('pie'));  
chart.draw(data, options);  
};
}
</script> 

这个问题已经存在2年了,但仍然没有答案。让我为你的问题提供一个可能的解决方案。

谷歌有切片选项:自定义切片颜色和字体颜色。可以使用所有切片的数组来自定义它们,也可以使用切片的索引来自定义单个切片。

slices: [{color: 'black'}, {}, {}, {color: 'red'}]
or
slices: {0: {color: 'black'}, 3: {color: 'red'}}

如果颜色作为变量传递,则可以使用此选项动态更改颜色。

这是切片颜色的谷歌参考页面。饼图

最新更新