I need to display google chart with dynamic json data. In this case it is a gauge chart with only one json item:
{
"Label": "1",
"Waterlevel": "82"
}
My code generates no error. But also no chart will be generated.
<script type="text/javascript">
google.load('visualization', '1', {packages: ['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: 'getWaterLevel',
dataType: 'JSON',
success: function (jsonData) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Waterlevel');
for (var i = 0; i < jsonData.length; i++) {
data.addRow([jsonData[i].Label, jsonData[i].Waterlevel]);
}
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('waterlevel_div'));
chart.draw(data, options);
console.log(jsonData);
}
});
}
google.setOnLoadCallback(drawChart);
</script>
<div id="waterlevel_div" style=""></div>
the values for Waterlevel in the json are represented by strings,
which need to be converted to numbers.
try using parseFloat...
parseFloat(jsonData[i].Waterlevel)
EDIT: Seems to work fine here, with hard-coded json.
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var jsonData = {
"Label": "1",
"Waterlevel": 82
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Waterlevel');
var row = [];
for (var key in jsonData) {
row.push(jsonData[key]);
}
data.addRow(row);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('waterlevel_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="waterlevel_div"></div>
Note: you're using an old version of google charts, which should no longer be used.
recommend using the newer library loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
instead of 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 from now on.
this will only change the load statement, see Update Library Loader Code...
Related
I would like to lead with google charts is brand new to me and I could be making a really dumb mistake. I have been working on this all day and no matter what I do, I can't get my google chart to draw using my json data. I think it has something to do with the columns and rows. I've made alot of changes different ways and I've given up at the below information. I'm not getting any errors but my chart isn't loading. I've looked at so many threads and examples now that nothing is making sense. Any help is appreciated!
<div class="col-lg-12">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieDisconnectReasonsChart" style="min-height:271px"></div>
</div>
<script>
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var jsonData = $.ajax({
url: "/Reports/RunDisconnectReasonsReport",
type: "POST",
dataType: "json",
data: {
openDate: #Html.Raw(Json.Encode(Model.OpenDate)),
closeDate: #Html.Raw(Json.Encode(Model.CloseDate)),
},
})
.done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("string", "SY_DESCRIPTION");
data.addColumn("number", "TOTAL");
data.addColumn("number", "PERCTWODEC");
data.addColumn("number", "PERC");
data.addColumn("number", "ErrMsg");
Object.keys(jsonData).forEach(function (row) {
data.addRow([
row.SY_DESCRIPTION,
row.SY_OPEN_LBL,
row.TOTAL,
row.PERCTWODEC,
row.PERC,
row.ErrMsg
]);
});
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
debugger;
chart.draw(data, options);
});
};
</script>
the data format for a pie chart only allows for two data table columns.
one string and one number.
unless you're providing a custom tooltip, then a third string column is allowed.
next, you're manually adding columns and rows to the data table,
so you need to remove the jsonData variable from the constructor, here...
from...
var data = new google.visualization.DataTable(jsonData); // <-- remove jsonData
to...
var data = new google.visualization.DataTable();
if you want to create the data table directly from json,
the json must be in a specific format, found here...
Format of the Constructor's JavaScript Literal data Parameter
with the above method, you would not need to manually add columns and rows,
and the chart would be faster, depending on the amount of data anyway...
try removing the extra columns and correcting the constructor,
and it should work, similar to the following working snippet...
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("number", "TOTAL");
data.addRow([
'CAT A',
2
]);
data.addRow([
'CAT B',
6
]);
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
chart.draw(data, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieDisconnectReasonsChart" style="min-height:271px"></div>
EDIT
in the done method,
it appears your looping on the keys of your json object.
Object.keys(jsonData).forEach(function (row) {
instead, loop on the json object itself.
jsonData.forEach(function (row) {
see following snippet...
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var jsonData = $.ajax({
url: "/Reports/RunDisconnectReasonsReport",
type: "POST",
dataType: "json",
data: {
openDate: #Html.Raw(Json.Encode(Model.OpenDate)),
closeDate: #Html.Raw(Json.Encode(Model.CloseDate)),
},
}).done(function (jsonData) {
var data = new google.visualization.DataTable();
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("number", "TOTAL");
jsonData.forEach(function (row) {
data.addRow([
row.SY_DESCRIPTION,
row.TOTAL
]);
});
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
chart.draw(data, options);
});
};
I want to add data from json file to chart js in (django) but it do not appear
in our file placed in static folder
<canvas id="canvas" width="80" height="30"></canvas>
$.getJSON("JSONnigberOfPopulition.json", function (json) {
var labelsChart = json.map(function(item) {
return item.AvgTravelTime;
});
var dataChart = json.map(function(item) {
return item.Pop_ofNeigbor_riyadh;
});
Here as you can see this chart part :
var ctx = canvas.getContext('2d');
var config = {
type: 'line',
data: {
labels:labelsChart,
datasets:[{
label: 'Graph Line',
data: dataChart,
backgroundColor:'rgba(0, 119, 204, 0.3)'
}]
}
};
var myChart = new Chart(ctx,config);
});
I have a one question. google chart not draw.
Here is my code
<script>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/temhum",
dataType:"json",
}).done(function (jsonData) {
var data = new google.visualization.DataTable();
console.log(jsonData);
data.addColumn('string', 'date');
data.addColumn('number', 'temperature');
data.addColumn('number', 'humidity');
jsonData.forEach(function (row) {
data.addRow([
row.date,
row.temperature,
row.humidity
]);
});
var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));
chart.draw(data, {
width: 600,
height: 600
});
}).fail(function (jq, text, err) {
console.log(text + ' - ' + err);
});
}
</script>
Here is my console log
log
I don't know. why not draw chart. Does anybody know how to represent the data on real-time using node.js, google chart, and mysql?
the values in the json must match the column types
all three json columns come across as strings,
you can use the following to convert each to the correct type...
data.addRow([
new Date(row.date),
parseFloat(row.temperature),
parseFloat(row.humidity)
]);
Think you. I solved problem
Solution is ..
sungyong & WhiteHat Code Mix
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/temhum",
dataType: "json",
}).done(function(jsonData) {
var data = new google.visualization.DataTable(jsonData);
console.log(jsonData);
data.addColumn('datetime', 'date');
data.addColumn('number', 'temperature');
data.addColumn('number', 'humidity');
console.log(data);
jsonData.forEach(function(row) {
data.addRow([
new Date(row.date),
parseFloat(row.temperature),
parseFloat(row.humidity)
]);
});
var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));
chart.draw(data, {
width: 600,
height: 600
});
}).fail(function(jq, text, err) {
console.log(text + ' - ' + err);
});
}
</script>
Trying to put together my first google line chart, with JSON api data, in this (shortened) format:
{"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}}
From what I can tell, it needs to be in the format used below:
<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([
['Datetime', 'Battery Voltage, (V)'],
['2017-10-09T00:00:00.000Z', 12.50],
['2017-10-09T00:01:00.000Z', 12.44],
['2017-10-09T00:02:00.000Z', 12.43],
]);
var options = {
title: 'Battery Voltage',
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>
My question is: how do I get my json data into the correct format? ie:
{
"cols":[
{"label":"Datetime","type":"datetime"},
{"label":"Battery Voltage, (V)","type":"number"},
],
"rows":[{"c":[{"v":"2017-10-09T00:00:00.000Z"}{"v":12.50}
{"c":[{"v":"2017-10-09T00:00:00.000Z"}{"v":12.50}
]
}
using javascript, you can transform the json with the following snippet...
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
the above will create an array as follows...
[
["Datetime","Battery Voltage, (V)"],
["2017-10-09T00:00:00.000Z",12.5],
["2017-10-09T00:01:00.000Z",12.44],
["2017-10-09T00:02:00.000Z",12.43]
]
which then can be used with static method --> arrayToDataTable
to create the data table
var data = google.visualization.arrayToDataTable(chartData);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var jsonData = {"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {
bottom: 48
},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="curve_chart"></div>
I have 2 tempsensors that send their temp every ten min to firebase.
My firebase is structured like this:
{
AB: {
-K9kbKg4iqzaGP_mbKIC: {
date: "05 Feb 2016 08:47:27 +0000",
value: "013.2"
},
BattLevel: {}
},
AC: {
-K9kaqlycXMDbH-LpVrH: {
date: "05 Feb 2016 08:45:19 +0000",
value: "009.4"
},
BattLevel: {}
}
}
I would like to create a Google chart
But i don't seem to get the Json parsing wright.
I can add the temp of 1 sensor to display if i set the json path to
https://tempraspberry.firebaseio. com/AB.json
/<script>
// onload callback
function drawChart() {
// JSONP request
var jsonData = $.ajax({
url: 'https://tempraspberry.firebaseio.com/AB.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var data1 = new google.visualization.DataTable();
data1.addColumn('datetime', 'Time');
data1.addColumn('number', 'Temp');
$.each(results, function (i, row) {
data1.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
//tweede chart
var jsonData = $.ajax({
url: 'https://tempraspberry.firebaseio.com/AC.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var data2 = new google.visualization.DataTable();
data2.addColumn('datetime', 'Time');
data2.addColumn('number', 'Temp');
$.each(results, function (i, row) {
data2.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
});
//einde tweede chart
});
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 300,
width: 600,
interpolateNulls: true
});
}
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
</script>
I get can't find variable data1 with the above code.
Looks like a scope issue, declare the DataTable up front, something like this...
function drawChart() {
var data;
var sensors;
sensors = ['AB', 'AC'];
data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Temp');
// start process
requestData();
function requestData() {
var nextSensor;
if (sensors.length > 0) {
nextSensor = sensors.pop();
$.ajax({
url: 'https://tempraspberry.firebaseio.com/' + nextSensor + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData);
} else {
loadChart();
}
}
function loadData(results) {
$.each(results, function (i, row) {
data.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
requestData();
}
function loadChart() {
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 300,
width: 600,
interpolateNulls: true
});
}
}
google.load('visualization', '1', {
packages: ['corechart']
});
google.setOnLoadCallback(drawChart);
Thanks with small adjustments it works now.
I now have 2 datatables that show on one Google Chart.
I know the code probably isn't pretty but it works :-)
<script>
function drawChart() {
var data1;
var data2;
var sensors;
sensors = ['AB', 'AC'];
data1 = new google.visualization.DataTable();
data2 = new google.visualization.DataTable();
data1.addColumn('date', 'Tijd');
data1.addColumn('number', 'Paleis Zora');
data2.addColumn('date', 'Tijd');
data2.addColumn('number', 'Buiten');
// start process
requestData();
function requestData() {
$.ajax({
url: 'https://tempraspberry.firebaseio.com/AB.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData);
}
//eerste datatable
function loadData(results) {
$.each(results, function (i, row) {
data1.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
requestData2();
}
//tweededatatable
function requestData2() {
$.ajax({
url: 'https://tempraspberry.firebaseio.com/AC.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData2);
}
//eerste datatable
function loadData2(results) {
$.each(results, function (i, row) {
data2.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
loadChart();
}
function loadChart() {
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 500,
width: 800,
interpolateNulls: true
});
}
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});