我正在通过查询输入到Google Sheet中的数据来创建一个线图,我需要添加数据标签,即图表上点旁边的小数字。我发现有很多文档介绍了如何在手动输入的数据表中绘制图表,但没有介绍如何在Google Sheet中查询数据。请帮助我。
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'URL'
);
query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: '',
height : 250,
width : '100%',
}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
正确,你要添加 注释.
这可以通过使用 注释栏作用.
注释列的作用,应该直接跟随它在数据表中所代表的系列列。
在这种情况下,由于你是从查询中获取数据的,所以我们可以使用一个 DataView
来使用计算列添加注释。
首先,我们创建数据视图。
var view = new google.visualization.DataView(data);
然后,我们使用 setColumns
方法,来添加查询中的列索引,以及我们计算出的注释列。
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
最后,我们需要使用视图来绘制图表。
chart.draw(view, options);
请看下面的片段...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'URL'
);
query.setQuery('SELECT A, B OFFSET 0'); //select specific cells from the table
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: '',
height : 250,
width : '100%',
};
// create data view with calculated annotation column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(view, options); // <-- use view to draw the chart
}
注意:当使用 google.visualization.LineChart
,你只需要 'corechart'
包。
的 'line'
包是给他们的 材料 线图-> google.charts.Line