Highcharts format json data from php script / unixtime - javascript

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.

Related

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.

Highcharts series visibility with csv data source

I am new to programming language so please consider my poor knowledge. Basically i am trying to use Highcharts for my project which takes data from a csv data source.
please take a look at:
flood forcast data
The chart shows 10 days flood forcast for a particular place. I want to have the ability to disable a data series by default, so that when you click on its legend item it shows, instead of hides. This will give me the ability to put many series on one graph, only show the Important ones, while allowing users to show additional series if they need. as an example: on load it will have day1, day3 and day5 "visible: true" and rest "visible: false." hope i made it clear
here goes my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="//code.jquery.com/jquery-1.7.1.js"> </script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" />
<title>Flood Forecast</title>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
$.get('data.csv', function(csv) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
type:'spline'
},
rangeSelector: {
selected: 1,
inputDateFormat: '%Y-%m-%d'
},
title: {
text: 'Flood Forcast'
},
legend: {
enabled: true,
align: 'right',
verticalAlign: 'middle',
layout: 'vertical',
borderColor: 'black',
borderWidth: 0.5,
itemDistance: 0
},
// data
data: {
csv: csv
},
}, function(chart) {
// apply the date pickers
setTimeout(function() {
$('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker()
}, 0)
});
});
// Set the datepicker's date format
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText) {
this.onchange();
this.onblur();
}
});
});
</script>
</head>
<body>
<div id="container" style="height: 600px; min-width: 600px"></div>
</body>
</html>
Thanks in advance.
You can do this with the visible property, just add to your options:
series: [{
visible: false
}, {
visible: true
}]
series represents your array of series, in this example has two series, the first hidden and the second visible. You can check this fiddle that uses data csv too:
http://jsfiddle.net/u4yaxk58/
Hope it helps!

how to put php variable as an element of list in javascript

I am working on a project that will display a bar chart. The bar chart is working perfectly but when I try to pass an integer php variable to javascript variable and add the variable as an element of a list isn't working. below is my code. I don't know what is wrong with my source code. I spend several hours finding for solution online but I don't get any.
Looking forward to see your response.
<html>
<head><title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
#container {
height: 400px;
min-width: 310px;
max-width: 800px;
margin: 0 auto;
}
</style>
<?php
//my php variable
$ab=6;
?>
<script type="text/javascript">
//assign the php variable to javascript variable
var za = <?php echo $ab; ?>;
$(function () {
$('#container').highcharts({
chart: {
type: 'column',
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
// I'm putting the variable as an element below, but it's not working
data: [za, 3, null, 4, 0, 5, 1, 4, 6, 3]
}]
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-3d.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="height: 400px"></div>
</body>
For what it's worth, you should avoid interacting with javascript in this way. PHP works better when you're interacting with HTML, and let javascript be separate (this goes halfway towards using a true templating system, which you should do):
<?php
// page setup goes up here:
$ab = 6; // name your variables at little more descriptively, I don't know what this does
?>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
#container { height: 400px; min-width: 310px; max-width: 800px; margin: 0 auto; }
</style>
<script type="text/javascript">
$(function () {
console.log($('#ab-variable').val());
$('#container').highcharts({
chart: {
type: 'column',
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
// We're referencing our hidden field in the HTML
data: [$('#ab-variable').val(), 3, null, 4, 0, 5, 1, 4, 6, 3]
}]
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-3d.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<!-- we're including our variable here, in HTML, rather than in the javascript -->
<input type="hidden" id="ab-variable" value="<?= $ab; ?>">
<div id="container" style="height: 400px"></div>
</body>
... you can then look int the HTML and see that your hidden field has the correct value. If it's still not working, then you've got a problem with your javascript setup using highcharts.
If you write your code this way, you get the added benefit of being able to create a separate javascript file that will be cached at the client and they won't have to download it every time.
As is, it doesn't look like there's any inherent problem with your code, but re-factoring (when it's warranted) can sometimes suss out little bugs. To confirm that this code should work the way you want, I've added a console.log() call to ensure that your javascript can see your variable. To see anything more than that you'll have to provide a link to your page so we can see any errors that might be popping up.

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

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

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