【发布时间】:2012-04-10 22:45:00
【问题描述】:
我做了什么
我已将 Google 图表添加到我的页面顶部。这将返回图表的图像。
我需要做什么
我只需要在同一页面上添加第二个图表。
问题
第二个图表的代码被忽略。我主要怀疑这是因为我错误地组合了每个图表的代码。
代码
第一个图表(线):
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Apples');
data.addColumn('number', 'Oranges');
data.addRows([
['Oct 11', 20, 0],
['Nov 11', 0, 0],
['Dec 12', 0, 20],
['Jan 12', 0, 10],
['Feb 12', 0, 10],
['March 12', 10, 10]
]);
// Set chart options
var options = {'width':960,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
</script>
第二张图表(饼图):
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
每个图表都在正文中使用具有唯一 ID 的容器 div 调用:
<div id="chart_div"></div>
我的问题
如何将这两个代码块拼接在一起?我尝试复制 drawChart() 并指定唯一的函数名称和变量,但无济于事。
【问题讨论】:
-
您应该将您的解决方案作为答案发布,而不是对您的问题进行编辑。回答您自己的问题非常好。
-
@Kevin Reid - 我重新发布了解决方案作为答案。我只能等待两天才能选择我自己的答案作为接受的答案。感谢您的提示。
-
我遇到了这个问题,发现这是因为我的 div 元素写成 而不是显式的开始/结束元素 。如果其他人在渲染多个图表时遇到问题,请检查。
标签: javascript charts