Javascript 用 JSON 绘制谷歌图表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7068349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
draw google charts with JSON
提问by neverlate
How can I retrieve and use a dataset for google charts if it was a separate JSON file?? I tried jQuery getJSON but couldn't get it worked.. Google Viz should use the JSON to draw a bar chart Is there a native google API way? or can I find a way using jQuery and how? Thanks
如果它是一个单独的 JSON 文件,我如何检索和使用谷歌图表的数据集?我尝试了 jQuery getJSON 但无法让它工作.. Google Viz 应该使用 JSON 来绘制条形图 是否有原生的 google API 方式?或者我能找到一种使用 jQuery 的方法吗?谢谢
// 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', 'Products');
data.addColumn('number', 'Automated');
data.addRows([
['Product 1', 85],
['Product 2', 75],
['Product 3', 90],
['Product 4', 40],
['Product 5', 40]
]);
// Set chart options
var pie_options = {'title':'How Much Automated our Products are?',
'width':520,'height':300
};
var bar_options ={'width': 620, 'height': 300,
'title': 'Products',
'hAxis': {'title': '% Automated', 'titleTextStyle': {'color': 'red', 'fontSize': 16}}
}
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
chart.draw(data, pie_options);
var chart = new google.visualization.ColumnChart(document.getElementById('barchart_div'));
chart.draw(data, bar_options);
}
回答by Arnaud Le Blanc
new google.visualization.DataTable(json)
works.
new google.visualization.DataTable(json)
作品。
Look the output of dataTable.toJSON()
for the correct structure to use.
查看 的输出以dataTable.toJSON()
获取要使用的正确结构。
So, if you have a getjson.php script on your server that returns correctly formatted json, you could do that:
因此,如果您的服务器上有一个 getjson.php 脚本返回格式正确的 json,您可以这样做:
$.getJSON('/getjson.php', function(json) {
var dataTable = new google.visualization.DataTable(json);
});