I'm trying to generate a line graph with the help of google chart. But, I see "table has no columns". I tried example given on google site and observed the same. Following is my code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonDataString = "{\"cols:\":{\"Time\":\"\",\"Sensor-1\":\"\",\"Sensor-2\":\"\",\"Sensor-3\":\"\",\"Sensor-4\":\"\"},\"rows\":[{\"1\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"2\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"3\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"4\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"5\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"6\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"7\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"8\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"9\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"10\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]}]}";
var jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'time - temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
Any idea, where am I going wrong?
Thanks.
Your JSON object isn't formatted properly to generate a datatable directly from it. The accepted JSON format is :
{
"cols": [
{"label":"Topping","type":"string"},
{"label":"Slices","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms"},{"v":3}]},
{"c":[{"v":"Onions"},{"v":1}]},
{"c":[{"v":"Olives"},{"v":1}]},
{"c":[{"v":"Zucchini"},{"v":1}]},
{"c":[{"v":"Pepperoni"},{"v":2]}
]
}
A nested JSON object with a 'cols' array containing X number of objects, where X = your number of columns, and a 'rows' array, containing Y number of 'c' nodes, where Y = your number of rows, and inside each 'c' node, Z number 'v' nodes, where Z = your number of columns.
You should check google documentation here :
Google JSON DATA
P.S Try replace your JSON string by the one provided in my example and you'll see that your line chart will be drawn as I don't see any errors in your code.
Related
I am currently querying a table from Google sheet which has a Date column. The date column in my dashboard has time info included, which I want to remove; also the starting date in my code is 12/18/2018 but my dashboard starts with one day earlier. 12/17/2018 16.00
My Data source looks like this:
My Dashboard looks like this:
My Code Looks like this.
Code.gs:
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[1];
var data1 = sheet.getRange('A2:F9').getValues();
var data2 = sheet.getRange('A2:F9').getValues();
var rows = {data1: data1, data2: data2};
var r = JSON.stringify(rows);
return r;
}
Line Chart multiple Table.html
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data1, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
May I know how to change my date to the right format removing the time and also ensure the correct starting date
Any help is much appreciated.
The actual problem has me stumped, but I do have a workaround; see modified code example below, with some additional error handling.
I've extensively tested the server-side function, and from its perspective there is absolutely no difference in the row object that is created whether the range starts at column 'I' or 'J'.
The problem manifests itself in the client-side success handler which, when column 'I' is included is essentially passed a null argument, note the whole object, not just the row.data1 part, is null.
The row object that is being passed from the server to the client is quite complicated (an object with 3 key value pairs, where the values are fairly long arrays). I can't see anything in the GAS documentation that disallows this: Legal parameters and return values are JavaScript primitives like a Number, Boolean, String, or null, as well as JavaScript objects and arrays that are composed of primitives, objects and arrays. So this could be a bug?
The workaround, illustrated in the code examples below is to stringify the object in the server-side function, and then parsing it back to an object in the client.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="table1"></div>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withFailureHandler(failure_callback).withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var data3 = google.visualization.arrayToDataTable(rows.data3, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: false, width: '50%', height: '100%'});
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data2, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data3, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
Code
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
//var firstrow = 6; //11th row
//var range = sheet.getRange(firstrow, 1, sheet.getLastRow() - firstrow + 1, 6);
//var data1 = range.getValues();
var d1 = sheet.getRange('A1:B5').getValues();
var d2 = sheet.getRange('I2:O4').getValues();
var d3 = sheet.getRange('I2:O4').getValues();
var rows = {data1: d1, data2: d2, data3: d3};
// Stringify the object
var r = JSON.stringify(rows);
return r;
}
I am trying to view Pie chart with JSON format data when I am trying to use Table chart is working fine
I think the problem is parsing the JSON but I do not know where it is exactly
I also checked questions on this topic but not using it just like that they are using PHP as server-side but not like that on the HTML Page with javascript
That is the code
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawChart,
packages:['table']
});
function drawChart() {
var jsonData = [
{"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
{"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
{"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
];
var gglData = [];
if (jsonData.length > 0) {
// load column headings
var colHead = [];
Object.keys(jsonData[0]).forEach(function (key) {
colHead.push(key);
});
gglData.push(colHead);
// load data rows
jsonData.forEach(function (row) {
var gglRow = [];
Object.keys(row).forEach(function (key) {
gglRow.push(row[key]);
});
gglData.push(gglRow);
});
}
var data = google.visualization.arrayToDataTable(gglData);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="table_div"></div>
</body>
</html>
first, you have to include package --> 'corechart'
next, check the data format for a pie chart,
the data needs to be in rows vs columns...
see following working snippet,
each key / value pair is added as a separate row,
then the group() method is used to aggregate...
google.charts.load('current', {
callback: drawChart,
packages:['corechart', 'table']
});
function drawChart() {
var jsonData = [
{"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
{"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
{"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
];
var gglData = [['Vehicle', 'Value']];
jsonData.forEach(function (row) {
Object.keys(row).forEach(function (key) {
gglData.push([key, row[key]]);
});
});
var data = google.visualization.arrayToDataTable(gglData);
var groupData = google.visualization.data.group(
data,
[0],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(groupData);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(groupData);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="table_div"></div>
I am trying to create a line chart of changes in prices every minute. I need to be able to pull the data from my site. I can't get the chart to load if I use datetime for the x axis.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "sampleData.json",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 480});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I can create a chart using the following for sampleData.json:
{
"cols": [
{"id":"","label":"X","pattern":"","type":"string"},
{"id":"","label":"Line 1","pattern":"","type":"number"},
{"id":"","label":"Line 2","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"1","f":null},{"v":3,"f":null},{"v":4,"f":null}]},
{"c":[{"v":"2","f":null},{"v":1,"f":null},{"v":2,"f":null}]},
{"c":[{"v":"3","f":null},{"v":1,"f":null},{"v":3,"f":null}]},
{"c":[{"v":"4","f":null},{"v":1,"f":null},{"v":1,"f":null}]},
{"c":[{"v":"5","f":null},{"v":2,"f":null},{"v":5,"f":null}]}
]
}
But when I try to change x to a datetime, it won't load.
{
"cols": [
{"id":"","label":"X","pattern":"","type":"datetime"},
{"id":"","label":"Line 1","pattern":"","type":"number"},
{"id":"","label":"Line 2","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":new Date(2017,0,1,12,1),"f":null},{"v":3,"f":null},{"v":4,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,2),"f":null},{"v":1,"f":null},{"v":2,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,3),"f":null},{"v":1,"f":null},{"v":3,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,4),"f":null},{"v":1,"f":null},{"v":1,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,5),"f":null},{"v":2,"f":null},{"v":5,"f":null}]}
]
}
You should remove the new keyword when working with JSON.
From google charts:
https://developers.google.com/chart/interactive/docs/datesandtimes
"When serializing data using the JavaScript DataTable object literal notation to build your DataTable, the new Date() constructor cannot be used. Instead, Google Charts provides a Date string representation that allows your date or datetime to be serialized and parsed properly when creating a DataTable. This Date string format simply drops the new keyword and wraps the remaining expression in quotation marks:
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
I'm trying to make a basic histogram with Google Charts, but for some reason it's not using the bin width that I set. Below is a code sample:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['MyData', 'Value']
, ['whatevs', .57]
, ['whatevs', .57]
, ['whatevs', .57]
, ['whatevs', .8]
]);
var options = {
title: 'My Histogram'
, legend: { position: 'none' }
, histogram: {
bucketSize: .1
}
};
var chart = new google.visualization.Histogram(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
and here's an image of what happens:
but what I would like to happen would be for the bins to be uniformly sized at a width of 0.1.
This appears to be a bug introduced in Charts API version 44. You can roll back to version 43 by specifying the version number when you load the library:
google.charts.load("43", {packages:["corechart"]});
It seems like this is the result of a bug that can be fixed by adding hAxis: { type: 'category' } to the options.
Here is my code to create google chart from csv data. code look fine but still there is some error.
Code looks fine but error is may be due to some jquery syntext. I appreciate if someone can help me
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart1-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Chart1-data.csv
Category,
A,34
B,23
C,14
D,57
E,18
Other,5
Error:
SyntaxError: missing ) after argument list
i.e. line where script ends
UPDATE: there was }); missing. Now no error but chart does not appear
Your closing brackets for $.get( should be }); not just };
$.get({
// code
});
And you're also missing a closing curly bracket to close your function.
Demo