I have a Google line chart which doesn't show up after loading the page. After the first resize everything works.
How can I get the chart show up after loading the page?
Data comes from locale text file on the server. This textfile holds the date/time and a sensor value. Textfile gets split and used as data for the chart.
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart () {
$.ajax({
url: 'Temp.ESP',
type: 'get',
success: function (txt) {
var dataArray = [['Name', 'Date']];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++) {
var tmpData = txtArray[i].split(/\s+/);
dataArray.push([tmpData[0], parseInt(tmpData[1])]);
}
var data = google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
var options = {width: '100%',
height: '40%',
legend: 'none',
colors: ['red'],
hAxis: {
textStyle:{color: 'white'}},
vAxis: {
textStyle:{color: 'white'}},
backgroundColor: { fill:'transparent' }};
$(window).resize(function(){
chart.draw(data,options);
});
}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
setInterval(function(){
$.get( "mydata.php", function( data ) {
$( "#mydata" ).html( data ); // this will replace the html refreshing its content using ajax
});
}, 1000);
/* Chart */
#chart{
width: 100%;
}
<div id="chart">
<div id="chart_div"></div>
</div>
thank you!
Hard to know what's going on without being able to run your code, but it could just be a simple css fix. Try changing the parent to a flex container at 100vw and the child chart at flex:1
#chart{
width: 100vw;
display: flex;
// adjust the padding accordingly
}
#chart_div {
flex: 1;
}
I forgot to call the draw function.
First call was in the resize function.
function drawChart () {
$.ajax({
url: 'Temp.ESP',
type: 'get',
success: function (txt) {
var dataArray = [['Name', 'Date']];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++) {
var tmpData = txtArray[i].split(/\s+/);
dataArray.push([tmpData[0], parseInt(tmpData[1])]);
}
var data = google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
var options = {width: '100%',
height: '40%',
legend: 'none',
colors: ['red'],
hAxis: {
textStyle:{color: 'white'}},
vAxis: {
textStyle:{color: 'white'}},
backgroundColor: { fill:'transparent' }};
chart.draw(data,options); //forgot this call
$(window).resize(function(){
chart.draw(data,options);
});
}
});
Thanks for the inspiration!
Related
I create a Google charts, in php page
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});</script>
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["M", "COUNT",{ role: 'style' }],
var view = new google.visualization.DataView(data);
var options = {
width: 200,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart1 = new google.visualization.ColumnChart(document.getElementById("columnchart_values1"));
chart1.draw(view, options);
document.getElementById("columnchart_values1").style.display = "block";
}
</script>
<div style="width:80%;"class="columnchart_values" id="columnchart_values1"> </div>
The graph is fine, but the page width varies - very large. Why?
enter image description here
My Google Sheet Data Looks like this
I am trying to create a Dashboard with 2 Tables and a Line chart based on my data.
I managed to create a single table and Line chart earlier obtained from same data range, but I am having difficulties creating 2 different tables whose data source is from the same google sheet but different cell range.
Here is my Code.
Code 1
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1qkDFf4sYMgPZhGAoEf7vrXbBPmno6Tt4UT_zd5M8xLo";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
var data1 = sheet.getDataRange({A6: F16}).getValues();
var data2 = sheet.getDataRange({A1: F4}).getValues();
var rows = {data1: data1,data2: data2};
return rows;
}
Code 2
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="line"></div>
<div id="table1"></div>
<div id="table2"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var options = {
title: 'SPC Chart',
legend: 'none',
chartArea: {
width: '60%'
},
vAxis: {
textStyle: {
fontFamily: 'Arial',
fontSize: 12
}
}
};
var chart = new google.visualization.LineChart(document.getElementById("line"));
chart.draw(data1, options);
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: true, width: '50%', height: '100%'});
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
}
</script>
</body>
</html>
I am quite new and unsure on how to proceed.
The following code helped me to achieve what i wanted.
Code 1
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1qkDFf4sYMgPZhGAoEf7vrXbBPmno6Tt4UT_zd5M8xLo";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
var data2 = sheet.getRange('A1:F5').getValues();
var firstrow = 6; // 6th row
var range = sheet.getRange(firstrow, 1, sheet.getLastRow() - firstrow + 1, 6);
var data1 = range.getValues();
//var data1 = sheet.getRange('A6:F15').getValues();
rows = {data1: data1, data2: data2};
return rows;
Code 2
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="line"></div>
<div id="table1"></div>
<div id="table2"></div>
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var options = {
title: 'SPC Chart',
legend: 'none',
chartArea: {
width: '60%'
},
vAxis: {
textStyle: {
fontFamily: 'Arial',
fontSize: 12
}
}
};
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
var chart = new google.visualization.LineChart(document.getElementById("line"));
chart.draw(data1, options);
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: true, width: '50%', height: '100%'});
}
</script>
</body>
</html>
I'm using Google Charts and I'm trying to add multiple charts to one json call.
The chart style is gauge.
The example below works for only one gauge "field1" I'm not that great with the charts but I did create a working example that updates.
What I want to add is two more gauges and the json array names would be Tlak,Vlhkost. So the json would look something like this {"created_at":"2017-04-19T17:05:54Z","entry_id":4381,"field1":"1.00\r\n\r\n","field2":"83"}
How would I go about adding one more gauges?
<html>
<head>
<title>Google Gauge - ThingSpeak</title>
</head>
<body>
<div id="container">
<div id="inner">
<div id="gauge_div"></div>
</div>
</div>
</body>
</html>
//css
<style type="text/css">
body { background-color: #FFFFFF; }
#container { height: 100%; width: 100%; }
#inner { }
#gauge_div { margin: 0 auto; }
</style>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
// set your channel id here
var channel_id = 248987;
// set your channel's read api key here if necessary
var api_key = '16UK5LLONGR9LCR2';
// maximum value for the gauge
var max_gauge_value = 1023;
// name of the gauge
var gauge_name = 'Tlak';
// global variables
var chart, charts, data;
// load the google gauge visualization
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(initChart);
// display the data
function displayData(point) {
data.setValue(0, 0, gauge_name);
data.setValue(0, 1, point);
chart.draw(data, options);
}
// load the data
function loadData() {
// variable for the data point
var p;
// get the data from thingspeak
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feed/last.json?api_key=' + api_key, function(data) {
// get the data point
p = data.field1;
// if there is a data point display it
if (p) {
// p = Math.round((p / max_gauge_value) * 100);
displayData(p);
}
});
}
// initialize the chart
function initChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
chart = new google.visualization.Gauge(document.getElementById('gauge_div'));
options = {
width: 160, height: 160, min: 955, max: 1065,
majorTicks: [950, 980, 1010, 1040, 1060], minorTicks: 10,
greenFrom: 955,
greenTo: 1000,
greenColor: "#00e600",
yellowFrom: 1000,
yellowTo: 1020,
yellowColor: "#ff751a",
redFrom: 1020,
redTo: 1065,
redColor: "#FF0000"};
loadData();
// load new data every 15 seconds
setInterval('loadData()', 15000);
}
</script>
first, recommend using loader.js vs. the older library jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
this will only change the load statement, see following snippet...
next, start by loading the data, before building anything else
once the json data is received, use it to determine which charts to draw,
according the properties specified by field1, field2, etc...
see following working snippet...
// load the google gauge visualization
google.charts.load('current', {
callback: loadData,
packages:['gauge']
});
function loadData() {
// set your channel id here
var channel_id = 248987;
// set your channel's read api key here if necessary
var api_key = '16UK5LLONGR9LCR2';
// variable for the data point
var p;
// name of the gauge
var gauge_name;
// get the data from thingspeak
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feed/last.json?api_key=' + api_key, function(jsonData) {
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
if (key.indexOf('field') > -1) {
p = jsonData[key];
switch (key) {
case 'field1':
gauge_name = 'Tlak';
break;
case 'field2':
gauge_name = 'Vlhkost';
break;
default:
gauge_name = key;
}
displayData(key, p, gauge_name);
}
}
}
});
setInterval(loadData, 15000);
}
// display the data
function displayData(div, point, name) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
data.setValue(0, 0, name);
data.setValue(0, 1, point);
var chartContainer = document.getElementById('gauge_div_' + div) || null;
if (chartContainer === null) {
chartContainer = document.getElementById('inner').appendChild(document.createElement('div'));
chartContainer.id = 'gauge_div_' + div;
chartContainer.className = 'gauge';
}
var chart = new google.visualization.Gauge(chartContainer);
var options = {
width: 160, height: 160, min: 955, max: 1065,
majorTicks: [950, 980, 1010, 1040, 1060], minorTicks: 10,
greenFrom: 955,
greenTo: 1000,
greenColor: "#00e600",
yellowFrom: 1000,
yellowTo: 1020,
yellowColor: "#ff751a",
redFrom: 1020,
redTo: 1065,
redColor: "#FF0000"
};
chart.draw(data, options);
}
body { background-color: #FFFFFF; }
#container { height: 100%; width: 100%; }
#inner { }
.gauge { margin: 0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="container">
<div id="inner"></div>
</div>
note: the chart container divs are added dynamically...
I was wondering how can I make linear function in javascript like if you search on google:
y=2x+7
I tried using google charts but it didnt work...
here is the code:
google.charts.load('current', {
packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawCurveTypes);
var x = 0;
var y = 0;
var h = window.prompt('enter a number');
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'linear');
data.addRows([
]);
for (var i = 0; i <= 5; i++) {
addRows('[x,y]');
x = x + h;
y++;
}
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
series: {
1: {
curveType: 'function'
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Thanks!
How can I set a legend and labels for my Google pie chart?
The deprecated method had this ability: https://developers.google.com/chart/image/docs/gallery/pie_charts
Also, how can I make it so that onclick the selected slice gets exploded from the pie a little?
Here's what I have so far:
<div id="pie_chart_div" style="width: 940px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(render_applicant_sources);
function render_applicant_sources() {
var data = new google.visualization.arrayToDataTable([["Source","Number of Applicants"],["Hospitality Online",222],["Indeed",22]]);
data.addColumn('string', 'Geocoder');
data.addColumn('number', 'Geocodes');
var chart = new google.visualization.PieChart(document.getElementById('pie_chart_div'));
var options = {
title: 'Scottsdale Resort & Conference Center from December 1, 2012 to December 1, 2013',
is3D: true,
colors: [ '#2483b3', '#AAC789', '#1E4147', '#437356', '#F34A53', '#FAE3B4' ],
titleTextStyle: { bold: false },
legend: { position: 'labeled' }
};
chart.draw(data, options);
google.visualization.events.addListener(chart, 'click', function(e){
var data = chart.getSelection();
if(data.length > 0) {
chart.setSelection([]);
}
});
}
</script>
http://jsfiddle.net/xHwZW/
You need to use a "select" event handler, and set the chart's slices.<slice index>.offset option:
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
if (selection.length > 0) {
if (!options.slices || !options.slices[selection[0].row]) {
// if this is the first time the user clicked on the pie,
// or if the user clicks on an unexploded slice,
// unexplode all slices and explode the selected slice
options.slices = [];
options.slices[selection[0].row] = {
offset: 0.4
};
}
else {
// otherwise the user clicked on an exploded slice, so unexplode all slices
options.slices = [];
}
chart.draw(data, options);
}
else {
options.slices = [];
chart.draw(data, options);
}
});
See working example: http://jsfiddle.net/asgallant/R8yAK/