HOW to use JSON file in chart js? - json

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

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

How to get Piwik Json Data and use it with chart.js?

I use the piwik php api to generate data like this:
[
{"label":"1680x1050","nb_visits":9,"nb_actions":53,"max_actions":27,"sum_visit_length":3051,"bounce_count":3,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":7,"sum_daily_nb_users":0,"segment":"resolution==1680x1050"},
{"label":"1440x900","nb_visits":1,"nb_actions":1,"max_actions":1,"sum_visit_length":0,"bounce_count":1,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":1,"sum_daily_nb_users":0,"segment":"resolution==1440x900"}
]
and i want to use chart.js to visualize this data, at the moment my code looks like this and doesn't work:
var chartjsData = [];
var chartjsLabel = [];
$.getJSON("piwik.php", function (json) {
///src = http://stackoverflow.com/questions/24696329/how-to-use-json-data-in-chart-js
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].nb_visits);
chartjsLabel.push(json[i].label);
}
});
var barChartData = {
labels :[chartjsLabel],datasets : [
{
fillColor : "rgba(220,280,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : chartjsData
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: barChartData,
});
can maybe someone give me a working example how to work with chart.js and piwik's json data, or a hint how to get this working, thanks alot!
I got it like this:
var label = [];
var data = [];
$.getJSON("piwik.php", function (json) {
for (var i = 0; i < json.length; i++) {
label.push(json[i].label);
data.push(json[i].nb_visits);
}
graph();
});
function graph(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
}
});
};

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