我从PHP脚本中的mysql数据库中提取数据,并使用谷歌图表以图形方式显示数据。当使用只有2个变量来处理的饼图或条形图时,它工作正常。现在我想使用ComboChart。我在表中有4个字段:名称,日期,数量,成本。我想要一个ComboChart,其中x轴是Date,条形图表示Quantity,线图表示Cost。
这是我到目前为止的代码。我该怎么做呢?在drawChart()函数中,x轴或y轴没有明确的顺序,所以我怎么知道我的哪些数据显示在哪里?这取决于您在mysqli_query期间选择数据的顺序吗?
// host, username, password and dbname are already declared
$conn = mysqli_connect($host, $username, $password);
if ($conn->connect_error) {
die("Could not connect: " . mysql_error()) . "<br>";
}
mysqli_select_db($conn, $dbname);
$qresult = mysqli_query($conn, "SELECT * FROM Scrap");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Quantity', 'type' => 'number'),
array('label' => 'Cost', 'type' => 'number')
);
$rows = array();
while ($r = $qresult->fetch_assoc()) {
$temp = array();
$temp[] = array('v' => (string) $r['Date']);
// Values of each slice
$temp[] = array('v' => (int) $r['Quantity']);
$temp[] = array('v' => (float) $r['Cost']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'YTD Controllable Scrap Costs',
seriesType:'bars',
series:{2: {type: 'line'}}
// width: 800,
// height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
答案 0 :(得分:0)
所以我测试了周围,我发现第一列是x轴,第二列,第三,第四列等在y轴上。条形图和线图没有显示的原因是因为在我的drawChart()函数中,它表示:series:{2: {type: 'line'}}
,数字2指的是y轴的第3个字段,因为它为零-索引。我没有为y轴设置第3个字段,因此我将其切换为series:{1: {type: 'line'}}
,现在我得到条形图和折线图。