Correct JSON structure for Google Line Chart - json

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>

Related

Google Charts - Not Drawing - JSON Response

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);
});
};

Draw google chart with dynamic data from json

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...

Google chart not draw

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>

Google map is not loading on a div hover

This code block is working well on page is loading--
<script type="text/javascript">
google.load("visualization", "1", { packages: ["map"] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Lat', 'Lon', 'Name'],
[22.1589, 90.1165, 'BARGUNA'],
[22.6953, 90.3538, 'BARISAL'],
]);
var options = {
showLine: false,
showTip: true,
zoomLevel: 7,
mapType: 'terrain'
};
var map = new google.visualization.Map(document.getElementById('map_canvas'));
map.draw(data, options);
}
</script>
This code block is for a specific div hover event. But it is not working--
<script>
$(function () {
$('#tab-dhakadivision').hover(function () {
google.load("visualization", "1", { packages: ["map"] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Lat', 'Lon', 'Name'],
[23.78069, 90.41932, 'DHAKA'],
[23.60113, 89.83923, 'FARIDPUR'],
[24.11119, 90.42584, 'GAZIPUR']
]);
var options = {
showLine: false,
showTip: true,
zoomLevel: 7,
mapType: 'terrain'
};
var dmap = new google.visualization.Map(document.getElementById('map_canvas'));
dmap.draw(data, options);
}
});
});
</script>
Any suggestion ?

google chart stacking not working

Here is my HTML
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var jsonDataObj = {
"rows":[
{"c":[{"v":"2001"},{"v":"43"},{"v":"43"}]},
{"c":[{"v":"2002"},{"v":"43"},{"v":"43"}]},
{"c":[{"v":"2003"},{"v":"43"},{"v":"43"}]},
{"c":[{"v":"2004"},{"v":"43"},{"v":"43"}]}
],
"cols":[
{"id":"","label":"Year","type":"string"},
{"id":"","label":"profits","type":"number"},
{"id":"","label":"expenses","type":"number"}
]
};
function drawChart() {
var jsonData = jsonDataObj;
var data = new google.visualization.DataTable(jsonData);
var options = {
width: 800, height: 480,
//isStacked:true,
title: 'Company Performance'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
If I enable isStacked option the pictuer shown is completely wrong
if I disable it the chart is fine
Let me know how to get the stacking to work.
after some testings I found the reason of the bug: you defined a strings in data instead of numbers, fixed page below:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var jsonDataObj = {
"rows":[
{"c":[{"v":"2001"},{"v":65},{"v":40}]},
{"c":[{"v":"2002"},{"v":67},{"v":43}]},
{"c":[{"v":"2003"},{"v":80},{"v":35}]},
{"c":[{"v":"2004"},{"v":97},{"v":47}]}
],
"cols":[
{"id":"","label":"Year","type":"string"},
{"id":"","label":"profits","type":"number"},
{"id":"","label":"expenses","type":"number"}
]
};
function drawChart() {
var jsonData = jsonDataObj;
var data = new google.visualization.DataTable(jsonData);
var options = {
width: 800,
height: 480,
isStacked: true,
title: 'Company Performance'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Please, have a look at this example https://jsfiddle.net/912jggdw/
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
["Category", "A", "Total" ],
["Planned", 500, 500 ],
["Achieved", 400, 600 ]
]);
var options = {
width: 300,
height: 400,
legend: {position: "none"},
bar: { groupWidth: '75%' },
isStacked: true,
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Another option would be using Google Image Charts.
And it is good because
1) it will work in all browsers including old ones, as it is a picture.
2) You can do Bullet Charts with it, when there is no option to do "Bullet Charts" in new Google Charts, and even the plain Diff Charts styled as "Bar and Column" does not work in latest versions of Firefox (I tried version 39).
Here is great example:
Read more about Google Image Charts here:
https://developers.google.com/chart/image/?hl=en