Google Visualization Line Chart using Google Sheet Code Example - google-visualization

I'm looking for sample code for using a Google Sheet as the source data and make a fairly simple line chart using Google Visualization.
I noticed that the new Google Sheets don't include a script in the "Share Chart" function, they offer a IFRAME and the width/height doesn't work. So, I'm looking to do it with Google Visualizations.
Here is my sample chart.
Thank you for the help.
Edited...
Here is my spreadsheet.
Here is my HTML file.
<html>
<head>
<script type="text/javascript">
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key=14MXilv-uhEAUxDzVB7qVCCmQYqkmWvqqaBOXeBsS04k&gid=0');
query.setQuery('SELECT A, B, C, D, E');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('linechart'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChart
});
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id="linechart"></span>
</body>
</html>
It doesn't draw. I've tried various selection in the spreadsheet like avoiding column A, no go. What am I doing wrong?

Here's some example code to get you started:
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key={spreadsheet key}&gid=0');
query.setQuery('SELECT A, B, C');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
You would need to replace the {spreadsheet key} in the URL with your own spreadsheet key (eg: 'http://docs.google.com/spreadsheet/tq?key=1234567890&gid=0') and change the query to select the appropriate columns from your spreadsheet.
In your page's HTML, you need to have a container div that matches the ID used when creating the chart ('chart_div' in this case):
<div id="chart_div"></div>

Related

Google Visualization - Select Handler not working

I'm hoping this is a problem that's really easy to fix. Having copied all of the necessary code from the Google Visualization site, everything is working with one exception. I have a data table where, if I select a row, the select handler is called - but I am unable to get table.getSelection() to work
I've seen a suggestion that I might need to include getChart(), but that doesn't fix it (at least not in any of the ways I tried).
In the extract below, I get the first alert message when selecting a row, but not the second, as the code stops running at the table.getSelection() line.
Can anyone suggest what the problem might be?
Many thanks!
<html>
</body>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable_1);
function drawTable_1() {
js_booking = <?php echo json_encode($arr_booking); ?>;
js_name = <?php echo json_encode($arr_name); ?>;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (i = 0; i < 5; i++) {
data.addRows([
[js_booking[i], js_name[i]]
]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
google.visualization.events.addListener(table, 'select', selectHandler);
}
function selectHandler(e) {
alert('A table row was selected');
var selection = table.getSelection();
alert('Selection identified');
}
</script>
</head>
<body>
<div id="table_div_1">Loading...</div>
</body>
<br>
</html>
don't really see a problem with the code, seems to work fine here.
only minor issue...
generally, chart events should be assigned after the chart is created but before the chart is drawn.
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (var i = 0; i < 5; i++) {
data.addRow(['Booking ' + (i + 1), 'Name ' + (i + 1)]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
google.visualization.events.addListener(table, 'select', selectHandler);
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
function selectHandler(e) {
console.log('A table row was selected');
var selection = table.getSelection();
console.log('Selection identified', JSON.stringify(selection));
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div_1"></div>

not enough columns to draw -google charts

I have tried to pass some array data to google charts but it says not enough columns to draw chart.here is my code.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1=someStr.replace(/(["'])(\d+)\1/g,"$2")
console.log(data1);
var data = google.visualization.arrayToDataTable([['year'],[data1]]);
console.log(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
</body>
</html>
Please help me to do this.
Thank in advance.
Your data has two columns: Month and a Number. ("JAN","1088626")
But you're only providing a header for one column: year
Plus, you need to pass an actual array to arrayToDataTable. (not a string)
Try something like this...
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1 = JSON.parse('[' + someStr.replace(/(["'])(\d+)\1/g,"$2") + ']');
// data array - add two column headings to data1
data1.splice(0, 0, ['month', 'number']);
// data table
var data = google.visualization.arrayToDataTable(data1);
// chart options
var options = {
title: 'My Daily Activities',
is3D: true
};
// chart
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
You are getting this error since invalid input data is passed into google.visualization.arrayToDataTable function. The provided regex /(["'])(\d+)\1/g fails while parsing the input string, i would suggest to parse input string with JSON.parse function.
google.visualization.PieChart object expects data to be provided in
the following format:
var data = google.visualization.arrayToDataTable([
['Name', 'Value'],
['<name1>', <value1>],
['<name2>', <value2>],
['<name3>', <value3>],
...
['<namen>', <valuen>]
]);
Below is provided the modified example:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var stringData = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data = JSON.parse("[" + stringData + "]");
data = data.map(function (item) {
item[1] = parseInt(item[1]);
return item;
});
data.splice(0, 0, ['year', 'hours']);
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(dataTable, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>

Draw separate barchart for subcategories using google visualization

I am trying to draw a bar chart using google visualization. I have 11 categories, out of those eleven categories 4 of them have subcategories. The Subcategories are different for different categories. For example:
a) Video
i. Subcategories: Netflix, YouTube, Vimeo, Vine,
DailyMotion
b) Email & Messaging
i. Subcategories: gmail, hotmail,
yahoomail
. . .
My requirement is, when onclick of one category on bar chart, the subcategories will display as another bar chart.
Can this be possible using google visualization? Please let me know.
Or is there any other way i can handel this?
Here is a really simple example of what you can do:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Value'],
['Videos', 1000],
['Mail', 1170]
]);
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'select', function(){
var selection=chart.getSelection();
if(selection.length == 1){
var row = selection[0].row;
var col = selection[0].column;
var cat = data.getValue(row,0);
drawSubChart(cat);
}
})
chart.draw(data, {});
}
function drawSubChart(cat){
var arr = [['SubCategory', 'Value']];
if(cat == 'Videos'){
arr.push(['Youtube', 700], ['DailyMotion', 300]);
}else if(cat == 'Mail'){
arr.push(['Gmail', 600], ['Hotmail', 570]);
}
var data = google.visualization.arrayToDataTable(arr);
var chart = new google.visualization.BarChart(document.getElementById('chart_div2'));
chart.draw(data, {});
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 500px; height: 300px;"></div>
<div id="chart_div2" style="width: 500px; height: 300px;"></div>

Google charts with Fusion Table Example error

Alright so I copy and pasted this example from google's chart tools documentation:
https://developers.google.com/fusiontables/docs/samples/gviz_datatable
I simply replaced their fusion table info with mine and am unable to get the table to appear.
This is what I have now with the fusion table set to public access:
<html>
<head>
<meta charset="UTF-8">
<title>Fusion Tables API Example: Google Chart Tools Data Table</title>
<link href="/apis/fusiontables/docs/samples/style/default.css"
rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['table'] });
function drawTable() {
var query = "SELECT 'fundraiser' as fundraiser, " +
"'price' as price, 'merchant' as merchant " +
'FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (team) {
query += " WHERE 'fundraiser' = '" + fundraiser + "'";
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
var table = new google.visualization.Table(
document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
google.setOnLoadCallback(drawTable);
</script>
</head>
<body>
<div>
<label>Scoring Team:</label>
<select id="fundraiser" onchange="drawTable();">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
</body>
</html>
I'm not sure what exactly was wrong with your query, but this works for me:
function drawTable () {
console.log('foo');
var query = 'SELECT fundraiser, price, merchant FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (fundraiser) {
query += ' WHERE fundraiser = \'' + fundraiser + '\'';
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
function init () {
// draw the table
drawTable();
// setup the fundraiser dropdown to redraw the table when the user changes the value
var el = document.querySelector('#fundraiser');
if (document.addEventListener) {
el.addEventListener('change', drawTable);
}
else if (document.attachEvent) {
el.attachEvent('onchange', drawTable);
}
else {
el.onchange = drawTable;
}
}
google.load('visualization', '1', {packages: ['table'], callback: init});
With this as the HTML:
<div>
<label>Scoring Team:</label>
<select id="fundraiser">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
I would suggest, however, that if you are going to have a filter like that, where your initial query is unfiltered, that you switch to using a CategoryFilter to filter your data in the browser instead of making a query to the server every time the user changes the filter. The only time making repeated queries to the server makes sense is when the total traffic to and from the server is likely to be substantially lower using multiple filtered queries than one single unfiltered query.

Can any tell me how add two needles in Gauge graph Using Google charts

I want to display two values in a single gauge graph using two needles. How can I do that.
Can any one please suggest me of doing it.
I have tried with following code But I am not success full.
And I got this following error.
GET http://5.39.186.164/%7B%22cols%22:[%7B%22label%22:%22Q7%22,%22type%22:%22nu…r%22%7D],%22rows%22:[%7B%22c%22:[%7B%22v%22:43%7D,%7B%22v%22:21%7D]%7D]%7D 404 (Not Found)
<!--Load the AJAX API -->
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['gauge']});
</script>
<script type="text/javascript">
var gauge;
var gaugeData;
var gaugeOptions;
function drawGauge() {
//var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
//var obj = eval ("(" + response + ")");
$.getJSON('<?php echo json_encode($response); ?>', function(json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
for (x in json) {
data.addRow([x, json[x]]);
}
//gaugeData = new google.visualization.DataTable(response);
gauge = new google.visualization.Gauge(document.getElementById('gauge'));
gaugeOptions = {
width: 2000,
height: 150,
greenFrom: 0,
greenTo: 50,
redFrom: 75,
redTo: 100,
yellowFrom:50,
yellowTo: 75,
minorTicks: 5
};
gauge.draw(gaugeData, gaugeOptions);
//chart.draw(data, options);
});
}
google.load('visualization', '1', {packages:['gauge'], callback: drawGauge});