how to draw charts with json file data in highcharts - highcharts

my json.data file is in the same directory as my index.html file. data.json file looks like this:
{
data:
[
[1369540800000,20]
]
}
when I do:
alert(JSON.stringify(jsonData, null, 4));
I get this back, so I get the values. Still dont know what is wrong.
{
"data":[
[
1369540800000,
10
],
[
1369541700000,
20
]
]
}
my html file including java script to build the charts is below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>HIGHTCHARTS</title>
<style>
body
{
font: 10px arial;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$.getJSON('data.json', function(jsonData) {
chartOptions.series = jsonData;
chart = new Highcharts.Chart(chartOptions);
});
var chartOptions = {
chart: {
renderTo: 'container'
},
xAxis: {
type: 'datetime'
},
series: []
};
});
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
I see the chart title but I dont see any charts or data points. What am I missing here?

Your data is not in the right format. Familiarize yourself with how to format data for Highcharts.
These may help:
http://api.highcharts.com/highcharts#series.data
http://docs.highcharts.com/#preprocesssing-data-from-a-file
Notably:
1) your dates must be either a javascript time stamp (epoch time, in milliseconds), or a date.Utc declaration
2) your structure needs to be like:
[[date, value],[date,value],[date,value]]

this is what I had to do to make it work:
<script src="js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area'
},
xAxis: {
type: 'datetime'
},
series: [{}]
};
$.getJSON('dude.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>

Related

Graph in popup and separate Div in Leaflet

I wonder if anyone can tell me what is wrong in my code please? I want to be able to select a polygon and show a graph in a popup using leaflet and highchart. I have managed to create the graph in the popup, but the line is missing on it, and I also get a separate div showing the same chart (and the line) at the bottom of my web page which I don't want. Can anyone tell me how to get the line to show on the chart in the popup and to remove the separate chart? Here is my code.enter code here
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--include leaflet CSS file-->
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<!--include Leaflet Javascript file-->
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="js/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src='http://unpkg.com/leaflet#1.0.2/dist/leaflet.js'></script>
<script src="js/esri-leaflet.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<!--Put a div element with a certain id where you want your map to be: -->
<div id="map" style="width: 1000px; height: 800px;"></div>
<div id="chartcontainer" class="highchart" style="width: 500px; height: 200px;"></div>
<!-- First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:-->
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads geoserver layer as WMS
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '2.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
L.geoJson(response, {
onEachFeature: function (feature, url) {
url.on('click', function(e){
var chartplotoptions ={
chart: {
type: 'line'
},
title: {
text: 'Growth'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
area: {
pointStart: -20,
threshold: 10,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: false
}
}
}
}
},
series: [{
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20150125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
};
$('#chartcontainer').highcharts(chartplotoptions);
url.bindPopup($('#chartcontainer').html());
url.openPopup();
});
}
}).addTo(mymap);
}
});
</script>
</body>
</html>
You don't need the div element in your HTML markup. You can create one on the fly in your onEachFeature function and add it to the popup. Also, you need to initialize your highchart after the popup has opened, not before. In code with comments:
new L.GeoJSON(feature, {
onEachFeature: function (feature, layer) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
layer.bindPopup(div);
// Handle event when popup opens
layer.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
// Now do the highcharts stuff
Highcharts.chart(e.popup.getContent(), { /**/ });
});
}
});
And don't forget to set the div's dimensions with CSS:
.highchart {
width: 500px;
height: 200px;
}

how do you create charts using highcharts javascript library

I am trying to use highcharts to build a charts. I have the below code:
my data.json file looks like this:
{"DATETIME":[1369540800,1369541700,1369542600,1369543500,1369544400,1369545300,1369546200,1369547100,1369548000,1369548900],"CPU":[14.84,13.6333333333333,14.7666666666667,13.5333333333333,17.8666666666667,15.9333333333333,14.2333333333333,13.3,10.8333333333333,9.76666666666667]}
HIGHTCHARTS
<style>
body
{
font: 10px arial;
}
</style>
<script src="jquery.min.js"></script>
<script src="js/highcharts.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON('data.json', function(data) {
$('#container').highcharts({
chart: {
type: 'line'
},
title: {
text: 'CPU UTILIZATION'
},
xAxis: {
categories: ['Date']
},
yAxis: {
title: {
text: '% CPU Utilization'
}
},
series: [{
data: data,
}]
});
});
});
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
I dont see any values, dada.json file is in the same directory as index.html file. Any ideas what I am missing here?
Your JSON should have data name instead of datetime. Morever I see only dates, not y values.
"DATETIME":
should be
"data":

Highcharts Scatter Plot Performance

I'm new to Highcharts and have been tinkering with it a bit on jsFiddle.
A fiddle independent example would look something like this:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'scatter',
zoomType: 'xy'
},
xAxis: {
type: 'datetime'
},
series: [{
color: 'rgba(223, 83, 83, .5)',
data:
[[Date.UTC(2012,10,15,12,25,47), 90.7000],
// Many more data points here, see fiddle for complete list
[Date.UTC(2013,2,7,11,37,18), 199.5000],
[Date.UTC(2013,2,7,11,37,18), 199.5000]]
}]
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="height: 300px"></div>
</body>
</html>
Anyways, I have a series that consists of a large set (~16k) of (datetime,float) Cartesian points that I wish to visualize on a scatter plot. I got what I wanted, but it appears to make my browser really sluggish. Particularly if I re-size the window or hover over tooltips. Looking for any advice or tips to optimize the performance or point out (no pun intended) something else I should be doing instead for this kind of visualization.
A couple of things you could do are to remove animation on the chart itself, and the tooltip. Also if you can get away with it, you could only render a tooltip for every 10th point.
http://jsfiddle.net/Jx5n2/3653/
chart: {
renderTo: 'container',
type: 'scatter',
zoomType: 'xy',
animation:false
},
tooltip:{
animation:false,
formatter:function(){
if(this.x % 10 != 0) return false;
return 'The value for <b>'+ this.x +
'</b> is <b>'+ this.y +'</b>';
}
},

Highstock with PHP MYSQL on Localhost will not render chart

My highstock will not open data in a chart on localhost. Does anybody has any idea why?
The chart displays no date. I have tried localhost, ipaddress, and still no luck.
//jsonp.php file
<?php
$host="localhost";
$username="root";
$password="";
$db_name="northwind";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select unix_timestamp(OrderDate) as datetime, Freight from TEST1 ORDER BY OrderDate ASC LIMIT 100";
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_array($result)) {
extract ($row);
$datetime *= 10000; // convert from Unix timestamp to JavaScript time
$data[] = array((float)$datetime,(float) $Freight);
}
$array2[] = json_encode($data);
///data2[] = json_decode($array2);
echo json_encode($data);
?>
////output from jsonp.php file
[[8364528000000,32.38],[8365392000000,11.61],[8367984000000,65.83],[8368848000000,51.3],[8369712000000,58.17],[8370576000000,22.98],[8371440000000,148.33],[8374032000000,13.97],[8374896000000,81.91],[8375760000000,140.51],[8376624000000,3.25],[8377488000000,3.05],[8380080000000,48.29],[8380944000000,146.06],[8381808000000,3.67],[8382672000000,55.28],[8383536000000,25.73],[8386128000000,208.58],[8386992000000,66.29],[8387856000000,4.56],[8388720000000,136.54],[8389584000000,98.03],[8392176000000,76.07],[8393040000000,6.01],[8393904000000,26.93],[8394768000000,13.84],[8395632000000,125.77],[8398224000000,92.69],[8399088000000,25.83],[8399952000000,8.98],[8399952000000,2.94],[8400816000000,12.69],[8401680000000,84.81],[8404272000000,76.56]]
////html file
html file-----below
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(function() {
$.getJSON('127.0.0.1/HIGH_STOCK/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'TEST DATA'
},
series : [{
name : 'TEST',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
//]]>
</script>
</head>
<body>
<script src="JS/highstock.js"></script>
<script src="JS/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Everything seems to be working fine with your code.
Demo
In your $.getJSON(...) you need to take care of the Same Origin Policy
You have not specified what errors you get or what problem are you facing, it is really difficult to help in such cases. Please consider posting a jsFiddle reproduction of the error
Ok, used the northwind database on PHPmyadmin with WAMP, on localhost, it is working. Forgive the sloppiness, it's late. If you have issues, please let me know.
//PHP
<?php
//read the northwind database nworders
$host="localhost";
$username="root";
$password="root";
$db_name="NORTHWIND";
$con=mysql_connect("$host", "$username", "")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select distinct unix_timestamp(ShippedDate) as datetime, Freight from nworders WHERE shipname LIKE '%Bon app%' ORDER BY datetime ASC LIMIT 50000 ";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
echo mysql_error();
}
$data = array();
while ($row = mysql_fetch_array($result)) {
extract ($row);
$datetime *= 1000;// convert from Unix timestamp to JavaScript time
$data[] = array($datetime, (FLOAT)$Freight);
}
$array2[] = json_encode($data);
echo json_encode($data);
?>
///
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('HTTP://localhost/HIGH/PHP_READ_TEST.PHP', function(data) {
// Create a timer
var start = + new Date();
// Create the chart
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function(chart) {
this.setTitle(null, {
text: 'Built chart at '+ (new Date() - start) +'ms'
});
}
},
zoomType: 'x'
},
rangeSelector: {
buttons: [{
type: 'day',
count: 3,
text: '3d'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
selected: 3
},
yAxis: {
title: {
text: 'Temperature (°C)'
}
},
title: {
text: 'Hourly temperatures in Vik i Sogn, Norway, 2004-2010'
},
subtitle: {
text: 'Built chart at...' // dummy text to reserve space for dynamic subtitle
},
series: [{
name: 'Temperature',
data: data,
pointStart: Date.UTC(2004, 3, 1),
pointInterval: 3600 * 1000,
tooltip: {
valueDecimals: 1,
valueSuffix: '°C'
}
}]
});
});
});
</script>
</head>
<body>
<script src="highstock.js"></script>
<script src="exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>

JQuery mobile and highcharts integration

Has anyone managed to integrate highcharts with jquerymobile properly?
If i request a page containing some chart directly (i.e. http://mysite.com/mobile/page.html) the charts will initialize and render as expected. Instead, if i try to navigate to the same page using the anchor links, the page renders but the charts don't. I am using the "pageshow" event to initialize the charts.
Any feedback will be largely appreciated!
I had this same problem when I first started coding with jQuery Mobile... You have to bind your scripts on pagecreate, ie:
$(document).delegate("#page-id", "pagecreate", function() {
// highcharts, etc.
}
With jQuery mobile you need to put your page specific scripts and styles inside the page-content div. See "Known Limitations" in documentation.
I have tried what Tsar mentioned and for me it worked. What I did was:
Added the script within the head tag,
and added the div with the ID(rederTo) used in the script within the "page-content".
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Acura</title>
<link href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
<script src="libs/hightcharts/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
</script>
</head>
<body>
<div id="ge" data-role="page">
<div data-role="header">
//header
</div>
<div data-role="content">
<div id="container"></div>
</div>
</div>
</body>
</html>

Resources