Using Jquery and JqPlot to plot graph from JSON file with data - javascript

I have a .json file (abc.json) and I want to plot graph using jqplot from two columns of this data. My approach is:
Converting json file data into array using jquery
Plotting graph from that array using jqplot
Then showing that graph on browser using html
However I am not able to do so as I am not very proficient in javascript.
My JSON data looks like follows:
[
{
"id":1,
"essid":"\"WiredSSID\"",
"mac":"08:00:27:b1:3e:4d",
"ip":"10.0.3.15",
"ss":-55,
"lon":-18.5333,
"lat":65.9667,
"alt":15.044444,
"acc":1,
"res":18058,
"pub_date":"2015-12-01 22:39:07.700953"
},
{
"id":2,
"essid":"\"WiredSSID\"",
"mac":"08:00:27:b1:3e:4d",
"ip":"10.0.3.15",
"ss":-55,
"lon":-18.5333,
"lat":65.9667,
"alt":15.044444,
"acc":1,
"res":16337,
"pub_date":"2015-12-01 23:13:52.639206"
},
However I want my javascript to read the data directly from JSON file and plot the graph for id vs res.
Below is a an incomplete code which I have written for this purpose which is missing some major process.
Can anyone please help me completing this code so that I can complete this academic project of mine. this would be really helpful.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="jquery.jqplot.css" />
<script src="jqplot.canvasTextRenderer.min.js" type="text/javascript"></script>
<script src="jqplot.canvasAxisLabelRenderer.min.js" type="text/javascript"></script>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="jquery.jqplot.js" type="text/javascript"></script>
<script src="jqplot.dateAxisRenderer.js" type="text/javascript"></script>
<script src="jqplot.categoryAxisRenderer.js" type="text/javascript" ></script>
<script src="jqplot.ohlcRenderer.js" type="text/javascript"></script>
<script src="jqplot.highlighter.js" type="text/javascript"></script>
<script src="jqplot.cursor.js" type="text/javascript"></script>
<script src="jqplot.pointLabels.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// The url for our json data
var url = 'mc_measurementne_new1.json';
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (data) {
ret = data;
}
});
var ID = [];
var Delay = [];
for (i = 0; i < ret.length; i++) {
// Save the data to the relevant array. Note how date at the zeroth position (i.e. x-axis) is common for both demand and supply arrays.
ID.push([ret[i].Date, ret[i].id]);
Delay.push([ret[i].Date, ret[i].res]);
}
var plot1 = $.jqplot('chart1', [ID, Delay], {
title: "Delay",
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString: '%d/%m/%Y'
},
label: 'Date'
},
yaxis: {
label: 'Delay'
},
y2axis: {
label: 'ID'
}
},
series: [
{ yaxis: 'yaxis', label: 'ID' },
{ yaxis: 'y2axis', label: 'Delay' }
],
highlighter: {
show: true,
sizeAdjust: 1
},
cursor: {
show: false
}
});
});
</script>
#{
ViewBag.Title = "jQPlot Demo";
}
<h2>#ViewBag.Title</h2>
<div id="chart1" style="height: 400px; width: 600px;"></div>
<script type="text/javascript" src="jquery.jqplot.min.js"></script>
<script type="text/javascript" src="jqplot.dateAxisRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.canvasTextRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.canvasAxisLabelRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.dateAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.categoryAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.ohlcRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.highlighter.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.cursor.js"></script>
</body>
</html>

Here is a working example. https://jsfiddle.net/9jk0jyvt/1/
I commented out the ajax request and replaced it with the json response you have provided above.
One thing to note is that you had the incorrect key for date. I switched it to pub_date.
I also swapped your axis labels to be correct.
$(document).ready(function() {
// The url for our json data
var url = 'mc_measurementne_new1.json';
data = [{
"id": 1,
"essid": "\"WiredSSID\"",
"mac": "08:00:27:b1:3e:4d",
"ip": "10.0.3.15",
"ss": -55,
"lon": -18.5333,
"lat": 65.9667,
"alt": 15.044444,
"acc": 1,
"res": 18058,
"pub_date": "2015-12-01 22:39:07.700953"
}, {
"id": 2,
"essid": "\"WiredSSID\"",
"mac": "08:00:27:b1:3e:4d",
"ip": "10.0.3.15",
"ss": -55,
"lon": -18.5333,
"lat": 65.9667,
"alt": 15.044444,
"acc": 1,
"res": 16337,
"pub_date": "2015-12-01 23:13:52.639206"
}];
populateGraph(data);
/*
$.ajax({
url: url,
dataType: "json",
success: function (data) {
populateGraph(data);
}
});
*/
function populateGraph(ret) {
var ID = [];
var Delay = [];
for (i = 0; i < ret.length; i++) {
// Save the data to the relevant array. Note how date at the zeroth position (i.e. x-axis) is common for both demand and supply arrays.
ID.push([ret[i].pub_date, ret[i].id]);
Delay.push([ret[i].pub_date, ret[i].res]);
}
var plot1 = $.jqplot('chart1', [ID, Delay], {
title: "Delay",
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString: '%d/%m/%Y'
},
label: 'Date'
},
yaxis: {
label: 'Delay'
},
y2axis: {
label: 'ID'
}
},
series: [{
yaxis: 'yaxis',
label: 'ID'
}, {
yaxis: 'y2axis',
label: 'Delay'
}],
highlighter: {
show: true,
sizeAdjust: 1
},
cursor: {
show: false
}
});
};
});

Related

Highcharts format json data from php script / unixtime

I wrote a php script with target to use $.getJSON() function.#
The live-temp-data.php create an json file with data like this:Data
This is the result : linechart
what am I doing wrong ? Code below.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Highcharts Example</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("live-temp-data.php", function(json) {
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'steinhagen-wetter.de'
},
subtitle: {
text: '2020'
},
yAxis: {
title: {
text: 'Temperature(°C)'
}
},
time:{
timezone: 'Europe/ Berlin'
},
xAxis: {
type: "datetime",
dateTimeLabelFormats: {
hour: '%H:%M',
},
},
series: [{
name: 'Outside Temp °C',
data: json
}]
});
});
});
});
</script>
</head>
</html>
1) Open the web console, and you will see the following message :
https://www.highcharts.com/errors/25/
If you browse this page, you will have the error message :
Can't find Moment.js library
Using the global.timezone option requires the Moment.js library to be
loaded.
So import that library, or remove this option, and that problem should be solved.
2) your HTML document is invalid, everything is in the head section, you should have a body section that contains your graph container.
3) your JSON is not valid : ["[1584713222000, 6.5]","[1584713572000, 6.6]","[1584713989000, 6.7]", ...
You should not have quotes around the data items.

Correct format of using csv data to plot highchart

I'm trying to create column chart using data imported from csv file. I have tried every possible solution on the Internet but couldn't figure out the solution to my problem. I'm trying to show Shop Name on x-axis and Sales on y-axis.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
body{
margin-top: 30px;
margin-left:40px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.3.5/papaparse.js"></script>
</head>
<body>
</div>
<div id="container" style="height: 400px"></div>
<script type="text/javascript">
$(function () {
$.get('stores.csv', function(csvdata) {
var data = Papa.parse(csvdata);
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "Sales Analysis"
},
xAxis: {
ShopName: []
},
yAxis: {
title: {
text: "Sales"
}
},
data: {
csv: data
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
}
});
});
});
</script>
</body>
</html>
csv file(stores.csv):
Longitude,Latitude,ShopName,ShopAddress,Sales
73.2350874,34.1990918,Abbotaqbad Civic Shopping Center,Mansehra Road Mandian,29719
74.3062887,31.5673136,Anarkali 1 9 - Babar Market,Anarkali,14212
74.3040372,31.5643123,Anarkali 263 - Babar Market,Anarkali,35928
74.4559979,31.5931715,Baghbanpura 239 - G T Road,Baghbanpura,49901
This is just to give you an example of how you can plot chart with Highchart while parsing .csv data. Code is simple and self explanatory.
<html>
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$.get('stores.csv', function(data) {
var lines = data.split('\n');
console.log(lines);
var shopNameData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
shopNameData[lineNo-1] = lineContent.split(',')[2];
}
});
var salesData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
salesData[lineNo-1] = parseFloat(lineContent.substring(lineContent.lastIndexOf(",")+1) );
}
});
console.log(shopNameData);
console.log(salesData);
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Sales Analysis'
},
subtitle: {
text: 'put subtitle here'
},
xAxis: {
categories: shopNameData,
crosshair: false
},
yAxis: {
min: 0,
title: {
text: 'Sales (in Rupees)'
}
},
tooltip: {
headerFormat: '<b>Shopname:</b> {point.x}<br/>',
pointFormat: '<b>{series.name}:</b> {point.y}<br/>'
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Sales',
data: salesData
} ]
});
});
</script>
</body>
</html>
.csv file used is:
Longitude,Latitude, ShopName,ShopAddress,Sales
73.2350874,34.1990918,Abbotaqbad Civic Shopping Center,Mansehra Road Mandian,29719
74.3062887,31.5673136,Anarkali 1 9 - Babar Market,Anarkali,14212
74.3040372,31.5643123,Anarkali 263 - Babar Market,Anarkali,35928
74.4559979,31.5931715,Baghbanpura 239 - G T Road,Baghbanpura,49901
Points to be noted
Note that in .csv there are no space after comma, so .csv must follow that or you have to edit the logic to form shopNameData and salesData
Host both .html and .csv at one place in some server. Otherwise, in Google Chrome, you will get CrossOrigin error.
Here is the snapshot of Chart if you will copy the html and name the .csv as stores.csv in same directory of html and host in some server.

jqPlot does not display the dates in the format it is being returned

I have a controller that returns List<int> countList and List<DateTime?> dayList upon making a selection on the controls.
return Json(new { stats = countList, days = dayList }, JsonRequestBehavior.AllowGet);
I have the below in my JavaScript file.
(function ($) {
function GetValues() {
//Get value of selections
var Start = $("#start").val();
var End = $("#end").val();
var sales = [];
$('.salelist:input:checked').each(function () {
sales.push(this.id)
})
var salecount = sales.join(",");
var submit = $("#submit").val();
$.ajax({
url: $("#submit").attr("data-url"),
data: { start: Start, end: End, Sale: salecount }
}).done(function (data) {
$('#chartdiv').empty();
testJqPlot(data.stats, data.days);
});
function testJqPlot(stats, days) {
$.jqplot.config.enablePlugins = true;
var plot = $.jqplot('chartdiv', [stats], {
series: [{ showMarker: false }],
title: 'Count By Date',
animate: true,
// Will animate plot on calls to plot1.replot({resetAxes:true})
animateReplot: true,
axes: {
xaxis: {
renderer: $.jqplot.CategoryDateAxisRenderer,
rendererOptions: { tickRenderer: $.jqplot.CanvasAxisTickRenderer },
label: 'Date',
tickRenderer: $.jqplot.CategoryAxisTickRenderer,
tickOptions:{
formatString: '%d-%m-%Y'
},
pad: 0
},
yaxis: {
label: 'Count'
}
},
series:[{lineWidth:4, markerOptions:{style:'square'}}],
highlighter: {
show: true
},
cursor: {
show: true,
tooltipLocation:'sw'
},
series: [{ lineWidth: 2
,markerOptions: { style: 'filledCircle', size: 0}
}]
}
);
} // end of TestJqPlot
}
$(document).ready(function () {
//Click event on the specified button
$("#submit").click(function () {
GetValues();
})
})
})(jQuery)
My view has this :
<div class="result" id="resultvol">
<div id="chartdiv" style="margin-top: 6%"></div>
</div>
I have included the following in my .cshtml file :
<script src="~/Scripts/jqPlot/jquery.jqplot.js" type="text/javascript"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.barRenderer.min.js" type="text/javascript"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js" type="text/javascript"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.dateAxisRenderer.min.js" type="text/javascript"></script>
<script src="~/src/plugins/jqplot.highlighter.js" type="text/javascript" ></script>
<script src="~/src/plugins/jqplot.cursor.js" type="text/javascript" ></script>
<script type="text/javascript" src="~/src/plugins/jqplot.canvasTextRenderer.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.canvasAxisLabelRenderer.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.dateAxisRenderer.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.highlighter.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.cursor.js"></script>
<script type="text/javascript" src="~/src/plugins/jqplot.pointLabels.js"></script>
<link href="~/Scripts/jqPlot/jquery.jqplot.css" rel="stylesheet" type="text/css" />
The chart is being returned as this :
jqPlot Chart
I am trying to have the x axis on the chart to display the dates in the correct format instead of "1-%m-%Y" and within the date range selected on the controls.
The graph plots correctly though.
I was able to resolve this error by removing the function from my ajax call - testJqPlot(data.stats, data.days);
And replaced this function with the entire script for jqplot.

How to create dynamic array fo array in javascript

I am reading data and loading in two dimensional array using following code by initializing 2d array (series)
where series is structure like as follows (highchart series)
series: [{
name: ''
data: []
}]
Manual code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>
$(function () {
var options = {
chart :{
type: 'polygon',
renderTo: 'container',
},
title: {
text: 'Height vs Weight'
},
yAxis: {
title: false,
gridLineWidth:0,
lineWidth:0,
labels:{
enabled: false
}
},
series: [{},{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data[0];
options.series[1].data = data[1];
var chart = new Highcharts.Chart(options);
})
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
But i want to initialize dynamic array so that i can insert arrays(data[i]) dynamically.
data.json
[
[
[
153,
42
],
[
149,
46
],
[
149,
55
],
[
152,
60
]
],
[
[
253,
142
],
[
349,
146
],
[
349,
155
],
[
352,
160
]
]
]
dynamic code:
series: [[]]
$.getJSON('data.json', function(data) {
for (i=0; i<data.length(); i++) {
series[i].data = data[i];
}
})
above code does not seem to be working. Pls help me how can i solve my problem.
You need to use the push() function to append dynamically
EDIT with second array to get the required "data" structure
// initialize array
var series = [];
$.getJSON('data.json', function(data) {
var temparray = [];
for (i=0; i<data.length; i++) {
temparray["data"] = data[i];
series.push(temparray);
}
})

Javascript HighCharts parsing CSV

I've tried similar examples through stackoverflow as well as Highcharts Support, however still cannot get a graph to display properly. Trying to display a spline graph with data from a csv file with format hour,temperature as shown below in an example:
22,84
23,83
00,82
01,81
02,79
03,77
04,75
Here is the currently html/javascript I have:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var time = [];
var temp = [];
$.get('forecast.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
time.push(parseInt(items[0]));
temp.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
title: {
text: 'Temperature Forecast'
},
xAxis: {
title: {
text: 'Hour'
},
categories: time
},
yAxis: {
title: {
text: 'Temperature'
}
},
series: [{
data: temp
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
</head>
<body>
<div id="container" style="width: 100%; height: 400px"></div>
</body>
My graph displays, however there is no data. Any ideas?
Thanks..
You need to add a two dimensional array as data. You can declare a global variable and add the data to that varible.
var chartData=[]
var dataTemp = new Array(parseInt(items[0]), parseInt(items[1]));
chartData.push(dataTemp);
and
series: [{
data: chartData
}]

Categories