Highcharts and JSON parameters - json

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/

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

Problem with fullCalendar : today's day disappears

i have a problem with fullcalendar. i don't know why but when i reload my page, i wait 2 seconds and today's day disappears and the line is shifting.
I do not know where the problem may come from.
Tanks a lot for your help
Edit: sorry for not having put code.
I thought it might be a classic problem that many had. Sorry again
Here is my code :
<!-- language: lang-js -->
document.addEventListener('DOMContentLoaded', function () {
var events = <?php echo json_encode($events) ?>;
var date = new Date();
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'fr',
plugins: ['interaction', 'dayGrid', 'list', 'googleCalendar', 'bootstrap', 'moment'],
themeSystem: 'bootstrap',
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,listYear'
},
navLinks: true,
selectable: true,
selectMirror: true,
select: function (arg) {
var start = moment(arg.start).format('YYYY/MM/DD HH:mm:ss');
console.log(start);
$("#date").val(start);
$('#addModal').modal();
if ($('#addModal').modal()) {
calendar.addEvent({
start: arg.start,
end: arg.end,
allDay: arg.allDay
});
$.ajax({
url: '<?= base_url(); ?>index.php/Admin/add_event',
data: {start: arg.start, end: arg.end},
type: "POST",
success: function (response) {
displayMessage("Updated Successfully");
}
});
}
calendar.unselect();
},
editable: true,
eventLimit: true,
displayEventTime: false,
events: events
});
calendar.render();
});
a screen capture
The problem is solved.
I found that it had a conflict between my bootstrap file and my js file where I had a :
window.setTimeout (function () {
$ (". alert"). slideUp (500, function () {
$ (This) .remove ();
});
}, 2000);
I think there was a class "alert" on the current day
Thanks a lot to ADyson

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>

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

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