Google Charts - Not Drawing - JSON Response - json

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

Related

Create Chart of 2 temp readings from firebase to Google charts

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

How can i draw simple line in column chart in google-charts API?

I have a simple column chart. using the google-charts API:
JS code:
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $str ?>);
var options = {
title: 'Business Optimization Per Predicted Conversion Rate',
bar: {groupWidth: "70%"},
colors: ['purple','grey'],
fontSize:20,
legend: { position: "none" },
width: 900,
backgroundColor: { fill: '#efeff0'},
};
var chart = new google.charts.Bar(document.getElementById('chart_div_1'));
chart.draw(data, google.charts.Bar.convertOptions(options));
My question is: How can i draw simple line here?
Horizontly to the X-axis.

Highcharts and JSON parameters

My file data.json is :
[{"metier":"Administratif","total":197555},
{"metier":"Canalisateur","total":4717},
{"metier":"Carreleur","total":15513}]
Please let me know how can i write my javascript code ?
I would like to create a chart with column ("metier" is X and "total" is Y)
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Thanks in Advance..
See the example of parser:
var output = [];
$.each(data,function(i,d){
output.push({
name: d.metier,
y: d.total
});
});
This code needs to be run in $.getJSON() callback body.
http://jsfiddle.net/sbochan/g7uzzyka/1/

Select which columns from CSV to graph with HighChart

As I was looking at the question How do I select which columns from my CSV to chart with HighChart? I tried to apply it using a csv file but I could not get it to work!
What am I doing wrong? Thank you in advance:
$(function () {
//var data = "Year,Month,Day,Hour,Time,kWh,Savings,Total kWh\n2013,02,06,11,11:00,0,0,308135\n2013,02,06,11,11:59,15,1.875,308150\n2013,02,06,12,12:59,27,3.375,308177\n2013,02,06,13,13:59,34,4.25,308211\n2013,02,06,14,14:59,32,4,308243";
var options = {
chart: {
renderTo: 'EXAMPLE',
defaultSeriesType: 'line'
},
title: {
text: 'Current Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: hassayampa.csv',
x: -20
},
xAxis: {
type: 'datetime'
},
yAxis:{
title: {
text: 'Temperature (\xB0C)'
},
//min: 0
},
legend:{
layout: 'vertical',
//backgroundColor: '#FFFFFF',
//floating: true,
align: 'left',
//x: 100,
verticalAlign: 'top',
//y: 70,
borderWidth: 0
},
series: [{
name: 'PRIM OUT TEMP',
data: []
}, {
name: 'SEC OUT TEMP',
data: []
}]
};
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
});
new Highcharts.Chart(options);
});
Here is the jsfiddle:http://jsfiddle.net/tonystinge/3bQne/1223/
I got it now...
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
// parsing here...
});
new Highcharts.Chart(options);
});
Your problem is the placement of the new Highcharts.Chart(options) call. $.get (like most ajax calls) is asynchronous So the new Highcharts will be called before it completes.
Change it to this:
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
new Highcharts.Chart(options); // this is now in the $.get callback function
});

Titanium Mobile Detailed view for row data

I am trying to create a detailed view of my json data. I am unsure of how to really approach it. I have the eventlistener, but I am unsure of how to pull data based on the name of the bar selected. Here is my json pull:
var win =Titanium.UI.currentWindow;
var data = [];
var xhr = Titanium.Network.createHTTPClient();
var barList = Titanium.UI.createTableView({
height:366,
width: 320,
top:0,
left:0
});
win.add(barList);
xhr.onload = function () {
var json = JSON.parse(this.responseText);
Ti.API.info(json.length);
for (var i = 0; i < json.length; i++) {
var row = Titanium.UI.createTableViewRow({
hasChild: true,
className: 'bar-row',
filter: json[i].bar.name
});
var titleLabel = Titanium.UI.createLabel({
text: json[i].bar.name,
font: {
fontSize: 14,
fontWeight: 'bold'
},
left: 70,
top: 5,
height: 20,
width: 210
});
row.add(titleLabel);
var addressLabel = Titanium.UI.createLabel({
text: json[i].bar.address,
font: {
fontSize: 10,
fontWeight: 'normal'
},
left: 70,
top: 25,
height: 40,
width: 200
});
row.add(addressLabel);
var iconImage = Titanium.UI.createImageView({
text: json[i].bar.logo_file_name,
width: 50,
height: 50,
left: 10,
top: 10
});
row.add(iconImage);
data.push(row);
row.addEventListener('click',function(e){
var detail = Ti.UI.createWindow({
title: e.rowData.title
});
detail.open({modal: true});
})
}
barList.data = data;
};
xhr.open('GET', 'http://site.com/db.json');
xhr.send();
JSON data:
I'm looking to pull the name, description, mon_special, tues_special, etc., for the bar selected
http://pastie.org/private/eyp9m5il6hrulbds76a8q
Simplest way to do this is attach the data to the row you created:
var row = Titanium.UI.createTableViewRow({
hasChild: true,
className: 'bar-row',
filter: json[i].bar.name,
barData : json[i].bar
});
Then access it through the event listener added to the TableView itself (don't use the rowData object of the event if you've created the row itself)
barList.addEventListener('click', function(e) {
// Get the row clicked, then get our custom attribute
var passedJSONBarData = e.row.barData;
// Now pass along through the window, or build the window here
var detail = Ti.UI.createWindow({
title: passedJSONBarData.title,
barData : passedJSONBarData
});
detail.open({modal: true});
});
I add the event listener to the table so that we only create the function once you may get some performance / memory savings using this approach.