使用Highcharts进行饼图。下面是它的JS代码:
$(document).ready(function () {
var chart;
var graphData = $("#graphContentdata").val();
console.log(graphData);
var options = {
chart: {
renderTo: 'graphContainer',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'SOV'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
}
chart = new Highcharts.Chart(options);
chart.series[0].setData("["+graphData+"]");
});
用于生成数据的PHP代码:
foreach ($sumArray as $key=>$value)
{
$sumArray[$key] = array_sum($value);
$percent = (number_format(($sumArray[$key]/$sovGrandTotal)*100,2));
$data[] = "['$key', $percent]";
}
$data = join(",", $data);
?>
<input type='hidden' id='graphContentdata' value="<?php echo $data; ?>">
我得到的数据格式是:
['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]
问题是:
chart.series[0].setData("["+graphData+"]");
没有创建图表,但是如果我复制粘贴来自graphData
变量的控制台的值,它的工作方式如下:
chart.series[0].setData([['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]]);
正在运作。
我在这做什么错误???
答案 0 :(得分:0)
问题是当您使用
时,您将数据作为字符串传递chart.series[0].setData("["+graphData+"]");
您需要set your data as an Array。您可以通过使用eval
转换字符串来完成此操作:
chart.series[0].setData(eval("["+graphData+"]"));
您也可以use jQuery to convert your String to JSON,但在这种情况下,您must use double quotes可以打开和关闭字符串:
$.parseJSON("[[\"www.quora.com\", 0.23],[\"www.slideshare.net\", 0.25],[\"me\", 99.52]]");