我正在尝试使用 Google 图表 API 将 Google 可视化查询转换为图表。
我正在尝试将其转换为图表,但我没有得到任何运气,我尝试过的是:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=TIMESERIES_GRAPH_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
我不明白为什么这没有将我拥有的数据转换成图表,非常感谢任何帮助
最佳答案
首先,需要发送查询并从响应中获取数据
接下来,要绘制饼图,第一列必须是字符串
请参阅以下工作片段,它使用数据 View 将第一列转换为字符串...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=TIMESERIES_GRAPH_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (data, row) {
return data.getFormattedValue(row, 0);
},
type: 'string',
label: data.getColumnLabel(0)
}, 1]);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(view, {
chartArea: {
height: '100%',
width: '100%'
},
height: 400
});
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
关于javascript - 如何将Google可视化查询转化为图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207978/