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);
}
})
Related
I have a query that get from SQL a list of names and theirs fields (OnTime & Delayed). If i use an echo $datosGrafico in php, it shows the below:
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ],
That part is fine. the problem appear once i try to put that variable in the google chart javascript. The script just stop working:
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = google.visualization.arrayToDataTable([
['Analista', 'On Time', 'Delayed'],
//(The variable $datosGrafico SHOULD GO HERE and avoid to insert every name mannualy)
['Agustin', 17, 1],
['Lucas', 6, 2],
]);
var options = {
width: 425,
height: 450,
chart: {
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
</body>
Any idea why this is happening?
I hope I understood you correctly. This works:
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff()
{
var data = google.visualization.arrayToDataTable(
[
['Analista', 'On Time', 'Delayed'],
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ]
]);
var options =
{
width: 425,
height: 450,
chart:
{
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
I've found the solution based on comments here! Thanks!
The php PDO query, return the variable:
$datosGrafico
I added some lines to save that variable result in a php file
$fichero = 'tpl\include\test.php';
$actual = $datosGrafico;
file_put_contents($fichero, $actual);
and then, i've just added the php code to read that file:
dataTable = new google.visualization.DataTable();
var newData = <?php include ('tpl\include\test.php')?>
var numRows = newData.length;
var numCols = newData[0].length;
// in this case the first column is of type 'string'.
dataTable.addColumn('string', newData[0][0]);
// all other columns are of type 'number'.
for (var i = 1; i < numCols; i++)
dataTable.addColumn('number', newData[0][i]);
// now add the rows.
for (var i = 1; i < numRows; i++)
dataTable.addRow(newData[i]);
Hope this help you in the future!
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.
I'm new to Highcharts JS.
I'm finding an issue in plotting "processed_json4".
All the other 4 plots (processed_json to processed_json3) appear on the graph. Any help would be much appreciated.
I have initialised 5 arrays and pushed the data received from JSON file into these arrays. The 5th plot however does not appear.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Highcharts data from JSON Response</title>
<style>
body{
margin-top: 30px;
margin-left:10px;
}
</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 type="text/javascript">
$(function () {
var processed_json = new Array(); //TS1
var processed_json1 = new Array(); //TS2
var processed_json2 = new Array(); //TS3
var processed_json3 = new Array(); //Processing Delay
var processed_json4 = new Array(); //Input-Output Delay
$.getJSON('http://localhost:8080/charts_demo/new4.json', function(data) {
// Populate series
for (i = 0; i < data.length; i++){
processed_json.push([data[i].timestamp1, data[i].val]);
processed_json1.push([data[i].timestamp2, data[i].val]);
processed_json2.push([data[i].timestamp3, data[i].val]);
processed_json3.push([((data[i].timestamp3)-(data[i].timestamp2)), data[i].val]);
processed_json4.push([((data[i].timestamp3)-(data[i].timestamp1)), data[i].val]);
}
// draw chart
$('#container').highcharts({
chart: {
type: "line"
},
title: {
text: "Streaming Flink Data"
},
xAxis: {
type: 'category',
allowDecimals: true,
title: {
text: "Timestamps"
}
},
yAxis: {
title: {
text: "Steps"
}
},
series: [{
name: 'Timestamp1',
data: processed_json
},
{
name: 'Timestamp2',
data: processed_json1
} ,
{
name: 'Timestamp3',
data: processed_json2,
},
{
name: 'Processing Delay',
data: processed_json3,
},
{
name: 'Input-Output Delay',
data: processed_json4,
}
]
});
});
});
</script>
</head>
<body>
<div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
Highcharts data load from a JSON using manual JSON Processing
</div>
<div id="container" style="height: 400px"></div>
</body>
</html>
new4.json looks like this:
[
{
"temperSensorData": "26.183021749996204",
"temperSensorUnit": "celsius",
"timestamp": "1370718629809",
"timestamp2": "1272913900562",
"timestamp3": "1272914212663",
"val": 0
},
{
"temperSensorData": "26.183021749996204",
"temperSensorUnit": "celsius",
"timestamp": "1370718629809",
"timestamp2": "1272923870899",
"timestamp3": "1272923910916",
"val": 1
},
.
.
.,{}
]
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
}
});
};
});
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
}]