I have this json output from the file countrows.php:
[
{
"time_stamp":"08:22:46 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:50 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:54 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:57 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:01 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:05 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:09 am",
"ph":"8",
"moist":"0"
}
]
The thing here is I want to show the time(coming from my json file) in my chart, specifically in the horizontal side. Something like the image below but the yellow green line shows the time from my json file.
By the way the following is my javascript code in my google chart,I need help on what to do with the following code:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
// onload callback
function drawChart() {
// JSONP request
var jsonData = $.ajax({
url: 'countrows.php',
dataType: 'json',
}).done(function (results) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('datetime', 'time_stamp');
data.addColumn('number', 'ph');
data.addColumn('number', 'moist');
$.each(results, function (i, row) {
data.addRow([
new Date(row.time_stamp),
parseFloat(row.ph),
parseFloat(row.moist)
]);
});
var chart = new google.visualization.AreaChart($('#chart').get(0));
chart.draw(data, {
title: 'Soil Analysis',
curveType: 'function',
displayAnnotations: true,
//legend: { position: 'bottom' }
pointSize: 10
hAxis: {format: 'Y,M,d,H';}
});
});
}
drawChart();
setInterval(drawChart, 10000);
the easiest way would be to change the first column to --> 'string'
data.addColumn('string', 'time_stamp');
also, since ajax is async, no need to assign to a variable,
remove this --> var jsonData =
and remove from argument to the data table constructor...
var data = new google.visualization.DataTable(jsonData); // <-- remove jsonData
try following snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
// onload callback
function drawChart() {
$.ajax({
url: 'countrows.php',
dataType: 'json'
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time_stamp');
data.addColumn('number', 'ph');
data.addColumn('number', 'moist');
$.each(results, function (i, row) {
data.addRow([
row.time_stamp,
parseFloat(row.ph),
parseFloat(row.moist)
]);
});
var chart = new google.visualization.AreaChart($('#chart').get(0));
chart.draw(data, {
title: 'Soil Analysis',
curveType: 'function',
pointSize: 10
});
});
}
drawChart();
setInterval(drawChart, 10000);
Related
//Ajax call
$(document).ready(function (data) {
$("#btnGo").click(function () {
console.log("ready!");
$.ajax({
url: '/api',
type: 'POST',
contentType: 'application/json',
dataType: 'JSON',
data: JSON.stringify({ startDate: $("#one").val(), endDate: $('#two').val() }),
success: function (data) {
var x = [data.x.count, data.x2.count, data.x3.count, data.x4.count]
//data.x.count is getting from an api call where it will show count like 5
drawChart(x)
}
});
});
});
//bar chart
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart(x) {
var data = google.visualization.arrayToDataTable([
['Tickets', 'Count', { role: "style" }],
['x1', x[0], "#b87333"],
['x2', x[1], "silver"],
['x3', x[2], "gold"],
['x4', x[3], "green"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
title: "Tickets",
width: 750,
height: 550,
bar: { groupWidth: "95%" },
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart"));
chart.draw(view, options);
}
i have defined this chart outside the ajax function
whenever i am calling server i am getting error in developer console(script.js:96 Uncaught (in promise) TypeError: Cannot read property '0' of undefined at drawChart)
after entering parameters and calling n number of times i am not seeing any errors in console
4)whenever i run server i dont want to see error.
Try to remove this line:
google.charts.setOnLoadCallback(drawChart);
This line will call your function drawChart without parameters. But it needs x to works properly, as you use it when you call google.visualization.arrayToDataTable.
You don't need it as you will call drawChart in your Ajax callback.
as you've discovered, the function gets called from the callback method without the data.
however, it is not a good idea to remove the callback,
as it is possible that the function may be called before google charts has fully loaded.
which would cause other errors.
there are a few ways to ensure google charts has loaded.
we can use the promise the load method returns.
as well, the load method will wait for the page to load by default.
so we can use google's load method in place of jquery's ready method.
recommend the following changes to ensure google charts has fully loaded,
and that the data gets properly passed to the chart.
google.charts.load("current", {
packages: ["corechart"]
}).then(function () {
var options = {
title: "Tickets",
width: 750,
height: 550,
bar: { groupWidth: "95%" },
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart"));
$("#btnGo").click(function () {
$.ajax({
url: '/api',
type: 'POST',
contentType: 'application/json',
dataType: 'JSON',
data: JSON.stringify({ startDate: $("#one").val(), endDate: $('#two').val() })
}).done(function (data) {
var x = [data.x.count, data.x2.count, data.x3.count, data.x4.count];
//data.x.count is getting from an api call where it will show count like 5
drawChart(x);
});
});
function drawChart(x) {
var data = google.visualization.arrayToDataTable([
['Tickets', 'Count', { role: "style" }],
['x1', x[0], "#b87333"],
['x2', x[1], "silver"],
['x3', x[2], "gold"],
['x4', x[3], "green"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2]);
chart.draw(view, options);
}
});
Scratch what i wrote earlier...
I did not see this line
google.charts.setOnLoadCallback(drawChart);
that gets called when the google chart is loaded but you're not passing x..
i removed this google.charts.setOnLoadCallback(drawChart); now not showing error.
I'm wondering how I could limit the MAX amount of items it can display to my chart to 5. I've got a cron job updating the .json daily, and currently it just tries to fit them all onto there.
This is my code:
<script>
google.charts.load("visualization", "1", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/server/database.json",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Players Hourly',
'is3D':true,
legend: 'bottom',
hAxis: {
minValue: 0,
format: 'long'
},
vAxis: {
minValue: 0,
scaleType: 'log',
format: 'long'
},
pointSize: 5,
series: {
0: { pointShape: 'circle' },
}
};
var chart = new google.visualization.LineChart(document.getElementById('serverstats'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
Thank you.
an easy way would be to use a data view and the setRows method.
then use the view to draw the chart.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setRows([0, 1, 2, 3, 4]); //<-- provide an array of the row indexes you want to see
...
chart.draw(view, options); //<-- use view here
EDIT
to show the last 5 rows...
var viewRows = [];
for (var i = data.getNumberOfRows() - 1; i > data.getNumberOfRows() - 6; i--) {
viewRows.push(i);
}
view.setRows(viewRows);
Am a beginner using google charts/js. My google chart below loads fine, however there are times when the chart area loads blank html, and when I refresh the page it displays correctly.
I'm not sure why this is. It seems to do this on all browsers. This seems to indicate it could be with Mozilla, but the problem persists...
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei.' '. $end.' '.$start); #imei=sys.arg[1] end=sys.arg[2] start=sys.arg[3]
?>
var jsonData = <?php echo $result; ?> //{"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {0: {viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
$(window).resize(function(){
drawChart()
});
});
</script>
when using a function inline / anonymously, although you can provide a name,
you will not be able to call that same function again, by it's name
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() { // <-- cannot call this again, no name needed
...
instead, declare the function separately, then pass a reference where needed,
using the name of the function
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
...
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
var jsonData = {"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {
0: {
viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {
viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {
0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_chart"></div>
I've been trying to use the Google Charts API to my Dashboard and see these error on firebug.
TypeError: google.visualization is undefined
Here is my JS code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Title', 'Values'],
['TBK', 8],
['Fluor Corp', 12],
['Fluor Group', 41],
['Bechtel', 39]
]);
var options = {
legend: 'none',
pieSliceText: 'none',
chartArea: {
width: '90%',
height: '90%',
},
colors:['#fa424a','#ac6bec','#fdad2a','#00a8ff','#46c35f','#e84f9a'],
slices: {
0: { color: '#fa424a' },
1: { color: '#ac6bec' },
2: { color: '#fdad2a' },
3: { color: '#00a8ff' }
},
pieHole: 0.8,
tooltip: { trigger: 'none' }
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
need to load the library before using the callback...
google.charts.load('current', {packages:['corechart']}); // <-- load
google.charts.setOnLoadCallback(drawChart);
you can also add the callback to the load statement...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
or use the promise the load statement returns...
google.charts.load('current', {
packages:['corechart']
}).then(drawChart);
Its a bit later but i have the same problem.
My problem was that the object google.visualization wasn`t ready when i call the function (i call in execution time, not with setOnLoadCallback).
So i call the function a bit later with an interval and its works for me:
function drawChart(){
timeout1 = setInterval(
function () {
data = new google.visualization.DataTable();
data.addColumn('string', 'Colum1');
data.addColumn('number', 'Colum2');
data.addColumn('number', 'Colum3');
data.addColumn('number', 'Colum4');
chart = new google.visualization.LineChart(document.getElementById('div_Chart'));
.
.
.
clearInterval(timeout1);
}, 100);
}
I hope its help u.
I'm working first time with google chart.i am trying to modify a bar chart to line chart in which i am facing an error "container is not defined". As a bar chart it is working fine and i am taking data as a json response my json response is like this.
[{"rate":0.7955,"month":"December"},{"rate":0.7822,"month":"November"},{"rate":0.7789,"month":"October"},{"rate":0.7915,"month":"September"},{"rate":0.7928,"month":"August"},{"rate":0.8002,"month":"July"},{"rate":0.8133,"month":"June"},{"rate":0.8218,"month":"May"},{"rate":0.8264,"month":"April"},{"rate":0.823,"month":"March"},{"rate":0.8201,"month":"February"},{"rate":0.8297,"month":"January"}]
and my js file is
var TUTORIAL_SAVVY = {
/*return google visualization data*/
getvisualizationData: function (jsonData) {
var point1, dataArray = [],
data = new google.visualization.LineChart();
data.addColumn('string', 'Rate');
data.addColumn('number', 'Marks in Mathematics');
data.addColumn({
type: 'string',
role: 'tooltip',
'p': {
'html': true
}
});
/* for loop code for changing inputdata to 'data' of type google.visualization.DataTable*/
$.each(jsonData, function (i, obj) {
point1 = "Rate : " + obj.rate + "";
dataArray.push([obj.month, obj.rate, TUTORIAL_SAVVY.returnTooltip(point1)]);
});
data.addRows(dataArray);
return data;
},
/*return options for line chart: these options are for various configuration of chart*/
getOptionForLinechart: function () {
var options = {
title:'Key Success Metrics over time across all channels',
'backgroundColor': 'transparent',
'width': 620,
'vAxis': {minValue:"0", maxValue:"100", gridlines:{count: 7} },
'chartArea': {top:"50", left: "40"},
'legend':{position: 'top', alignment: 'start' }
};
return options;
},
/*Draws a line chart*/
drawLineChart: function (inputdata) {
var lineOptions = TUTORIAL_SAVVY.getOptionForLinechart(),
data = TUTORIAL_SAVVY.getvisualizationData(inputdata),
chart = new google.visualization.LineChart(document.getElementById('student-line-chart'));
chart.draw(data, lineOptions);
/*for redrawing the line chart on window resize*/
$(window).resize(function () {
chart.draw(data, lineOptions);
});
},
/* Returns a custom HTML tooltip for Visualization chart*/
returnTooltip: function (dataPoint1) {
return "<div style='height:30px;width:150px;font:12px,roboto;padding:15px 5px 5px 5px;border-radius:3px;'>" +
"<span style='color:#68130E;font:12px,roboto;padding-right:20px;'>" + dataPoint1 + "</span>" ;
},
/*Makes ajax call to servlet and download data */
getStudentData: function () {
$.ajax({
url: '/bin/servlet/rate',
dataType: "JSON",
success: function (data) {
TUTORIAL_SAVVY.drawLineChart(data);
}
});
}
};
google.load("visualization", "1", {
packages: ["corechart"]
});
$(document).ready(function () {
TUTORIAL_SAVVY.getStudentData();
});
can anybody help ?