How to parse JSON into HighCharts line graph? - javascript

I am trying to parse the following JSON string remotely:
[{"name":"Object1","data":[1,2]},{"name":"Object2","data":[3,4]}]
I am doing so with the following code:
$(function () {
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'hits by time',
x: -20 //center
},
subtitle: {
text: 'Source:',
x: -20
},
xAxis: {
categories: ['8am', '9am', '10am', '11am', '12pm', '1pm',
'2pm', '3pm', '4pm', '5pm', '6pm', '7pm']
},
yAxis: {
title: {
text: 'Hits'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
$.getJSON('http://localhost:8080/jsonget', function(data) {
var series = {
data: []
};
$.each(data, function(i,item){
alert(item.name);
series.name = item.name;
$.each(item.data, function(j,dataitem){
alert(dataitem);
series.data.push(parseFloat(dataitem[i]));
});
});
options.series.push(series);
// Create the chart
var chart = new Highcharts.Chart(options);
});
});
});
The chart does not render, but does so when I substitute the remote portion for the CSV example on the site.
Does anyone know what the problem is?

As far as I can tell your data seems to be well formed. So, this should do it:
var chart;
$.getJSON('http://localhost:8080/UDPver/tagdiscover', function(data) {
// Populate series
options.series = data;
// Create the chart
chart = new Highcharts.Chart(options);
});

The problems is that the chart then is redrawn. So if you have other lines that is disabled (from legend), it will be visible agian when you do a update.
I have 5 lines in my graph. It is updated every second.
From the legend I can disable/remove some of the lines from the graph.
But using this method above (it works) the complete graph is redrawn and all lines is visible again.
Is it possible to just update the series (lines) and not the paramaters?
Like this (not working):
function doAjaxData() {
AjaxLoadingIcon(1);
$.ajax({
url: getAjaxUrl(1),
dataType: 'json',
cache: false,
async: true,
success: function (json) {
AjaxLoadingIcon(0);
gchartOptions.series = [];
gchartOptions.series = json;
// gchart = new Highcharts.Chart(gchartOptions);
gchart.render();
_updateTimer = window.setTimeout("doAjaxData()", 1000);
}
}
});
}

Atma.
You just should write just dataitem instead of dataitem[i] and it will work.
$.each(data, function(i,item){
alert(item.name);
series.name = item.name;
$.each(item.data, function(j,dataitem){
alert(dataitem);
series.data.push(parseFloat(dataitem[i]));
});
});

Related

Dynamically load in series HighCharts

I am trying to dynamically load in a number of series, depending on projects chosen by the user. I am using Laravel 5.2, PHP 5.6 and HighCharts.
I have managed to load in one JSON file, which is generated when the user selects projects. But I would like it if the JavaScript could parse the different series from the JSON file and dynamically load this into the series.
This is the code which I am using:
$(function () {
// Set up the chart
var processed_json = new Array();
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
name: 'Grades',
data: processed_json
}],
credits: {
enabled: false
}
});
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
});
My JSON is formatted like:
[{"key":"Math","value":6},{"key":"Biology","value":"8"},{"key":"English","value":"7"},{"key":"Gym","value":"4"}]
So I would like to have more JSONs like so, in one file to be parsed in the Javascript and be loaded in into the series.
Thank you!
EDIT
thanks for your reply. I have edited my code:
$(function () {
var processed_json = new Array();
var options = {
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
}],
credits: {
enabled: false
}
};
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
});
options.series[0].remove();
options.series[0].setData = {
name: 'Grades',
data: processed_json
}
var chart = new Highcharts.Chart(options);
chart.redraw(true);
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
But nothing is displayed anymore and the following error is given
TypeError: options.series[0].remove is not a function
I have also tried
var chart = new Highcharts.Chart(options);
chart.series[0].remove();
chart.series[0].setData = {
name: 'Grades',
data: processed_json
}
chart.redraw(true);
But this gives:
TypeError: Cannot set property 'setData' of undefined
I think highcharts has a method chart.addSeries for adding a new series. If you want to replace the current series with a new series, you can try removing first the current series using chart.series[0].remove( ) then add the new series with chart.addSeries. The parameter for the chart.addSeries can be an object like your
{
name: 'Grades',
data: processed_json
}
Then, define method with load data.. example:
function(chart) {
$.each(chart.series, function(i, v){
chart.series[i].remove(true);
});
chart.addSeries({your_data}, true);
}
check http://api.highcharts.com/highcharts/Chart.addSeries/Chart.addSeries
In my webapp, i use 10 of 15 types of graphs highchart and all dynamically load and work fine :) Highcharts is awesome.

How to add multiple series dynamically and update its data dynamically

my task is to add series dynamically and keep updating their data, which is received by ajax calls.
i know series can be added dynamically by declaring highchart funciton global. and using series.addseries() function , and also data can be updated by using settimout request to ajax call and updating points by using series.addpoint() function.
i have done both the work separably. but when i combine both the technique, data is not added to highchart. i have done lot of research on this, and i am not finding reason for not adding the data. infact script hang the browser.
i have checked the series object, which show x-data and y-data are processed. only difference i find is isDirty field and isDirtydata field are set to true. dont know the reason.
here is the full code
var serverUrl = 'http://'+window.location.hostname+':8000'
Highcharts.setOptions({
global: {
useUTC: false
}
});
data={}
$(document).ready(function(){
$(function () {
console.log("highcharts")
$('#first').highcharts({
chart: {
type: 'spline',
//marginRight: 150,
marginBottom: 5,
events: {
load: requestData(data)
}
},
title: {
text: 'Server Monitroting Tool'
},
subtitle: {
text: 'Cpu usage, Memory Usage,Disk Usage,Mongo Usage'
},
xAxis: {
type: 'datetime',
categories: ['TIME'],
dateTimeLabelFormats : {
hour: '%I %p',
minute: '%I:%M %p'
}
},
yAxis:{
showEmpty:false
},
legend:
{
backgroundColor: '#F5F5F5',
layout: 'horizontal',
floating: true,
align: 'left',
verticalAlign: 'bottom',
x: 60,
y: 9,
shadow: false,
border: 0,
borderRadius: 0,
borderWidth: 0
},
series: {}
});
});
from_date=new Date().getTime()-60000;
function requestData(data)
{
if(!data)
{
console.log("default ")
}
else
{
console.log("requesting")
$.ajax({
url:serverUrl+'/api/fetch_params/',
type:'GET',
data:data,
success:function(response)
{
console.log("in success")
//data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
var id=data['sub-type']+data['param']
var series = chart.get(id)
shift = series.data.length > 100; // shift if the series is longer than 300 (drop oldest point)
response= $.parseJSON(response)
var x=data['sub-type']
all_data=response.response.data[x]
// console.log(new Date(from_date),'latest timestamp')
console.log(series)
console.log("data",all_data)
from_date=all_data[all_data.length-1][0]
// console.log(from_date)
// series.isDirty=false
// series.isDirtyData=false
for (var i = 0; i < all_data.length; i++)
{
series.addPoint({ x: all_data[i][0],y: all_data[i][1],id: i},false,shift);
}
console.log("series object",series)
// chart.redraw();
console.log(" parameter",data)
data['from-date']=from_date
console.log("data",series.data)
// console.log(chart)
setTimeout(requestData(data), 10000);
console.log("out of success")
},
cache:false,
error:function()
{
console.log("err")
}
});
}
}
$.ajax({
url:serverUrl+'/api/fetch_all_servers/',
type:'GET',
success:function(response){
response = $.parseJSON(response)
sd = response.response.all_servers
$('input[name=select_menue]').optionTree(sd)
},
error:function(){
console.log('error')
}
});
$('.param-button').live('click',function(e){
e.stopPropagation()
})
$('param-select').live('hover',function(){
$(this).find('.type-select').show()
});
$('.final_value').live('change',function(){
select_name = 'select_menue_'
param_list = []
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
while(param){
param_list.push(param)
select_name += '_'
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
}
console.log(param_list,"param_list")
from_date=new Date().getTime()-300000 //5 minute data
hostname=param_list[0]
TypeOfParameter= param_list[1]
sub_type_parameter=param_list[param_list.length-1]
data = {'type':TypeOfParameter,'hostname':hostname,'param':sub_type_parameter,'from-date':from_date}
var sub_type;
if(param_list.length==4){
sub_type=param_list[2]
data['sub-type'] = sub_type
}
else
{
sub_type=sub_type_parameter
}
// console.log(hostname,TypeOfParameter,sub_type,sub_type_parameter)
data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
requestData(data)
$('#loadingmessage').show(); // show the loading message.
chart = $('#first').highcharts();
if(TypeOfParameter=='cpu')
{
console.log("adding axis")
chart.addAxis({ // Primary yAxis
id:'Cpu_axis'+sub_type_parameter,
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#89A54E'
}
},
title: {
text: "core "+ sub_type+ " "+sub_type_parameter,
style: {
color: '#89A54E'
}
},
lineWidth: 1,
lineColor: '#08F'
});
console.log("adding series")
chart.addSeries({
id:sub_type+sub_type_parameter,
name: "core "+sub_type+" "+sub_type_parameter,
data :[],
tooltip : {
valueSuffix: ' %'
},
yAxis:'Cpu_axis'+sub_type_parameter
})
console.log("series out")
}
if(TypeOfParameter=='memory')
{
chart.addAxis ({
id:'memory'+sub_type_parameter,
labels:{
formatter: function() {
return this.value +'%';
},
style: {
color: '#89C54F'
}
},
title: {
text:sub_type+" "+sub_type_parameter
},
lineWidth: .5,
lineColor: '#08F',
opposite: true
});
chart.addSeries({
id:sub_type+sub_type_parameter,
name: sub_type+'memory usage',
data: [],
tooltip: {
valueSuffix: '%'
},
yAxis:'memory'+sub_type_parameter
});
}
if(TypeOfParameter=='disk')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'disk Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'disk',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'disk',
data: []
}]
});
}
if(TypeOfParameter=='db')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'mongo Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'mmongo',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'mongo',
data: []
}]
});
}
if(TypeOfParameter=='redis')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'redis Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'redis',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'redis',
data: []
}]
});
}
$('#loadingmessage').hide(); // hide the loading message
}
)
});
i am stuck on this problem for quite a while. and still not able to figure out the solution.
here is the full code link
someone please please help. feeling frustrated ..:-(
As you know the addPoint method is bit dangerous when dealing with quite lots points. It is recommended to disable redraw per point when dealing with many new points - more info http://api.highcharts.com/highcharts#Series.addPoint() , I notice you are doing that already in the loop statement, but why did you commented out? have you tried enabling again. Make sure chart.redraw works by adding a new redraw chart event, and set an alert or console log.
Also you may try using, below as part of ajax, instead of cache:false. I had some problems in past.
headers: { 'Cache-Control': 'no-cache' }
Cheers

addPoint using highcharts (javascript)

I have started working with highcharts.js, but fails to add new points my bar graph:
Every time it goes into addPoint, Firefox freezes :(
I am using Firebug, and when it tries to addPoint, it always freeze :(
// if no graph
if (! charts[0])
{
// make chart table
var round_ids = [];
var total_players = [];
var total_bets = [];
$.each(last_rounds_cache.last_rounds_data, function(index, value)
{
round_ids.push(Number(value[0]));
total_players.push(Number(value[2]));
total_bets.push(Number(value[3]));
}
)
charts[0] = new Highcharts.Chart({
chart: {
renderTo: 'players_per_round',
type: 'column',
events: {
click: function(e) {
// find the clicked values and the series
var x = e.xAxis[0].value,
y = e.yAxis[0].value,
series = this.series[0];
// Add it
series.addPoint([x, y]);
}
}
},
title: {
text: 'Players/Bets per Round'
},
xAxis: {
categories: round_ids,
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 10,
y: 10,
floating: false,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Players',
data: total_players
}, {
name: 'Bets',
data: total_bets
}]
});
}
else
{
if (newChartsPoints.length > 0)
{
$.each(newChartsPoints, function(index, value)
{
// retreive data
var temp_round_id = value[0];
var temp_total_players = value[1][0];
var temp_total_bets = value[1][1];
// add points
var series = charts[0].series;
series[0].addPoint([temp_round_id, temp_total_players], false);
series[1].addPoint([temp_round_id, temp_total_bets], false);
// add categories
categories = charts[0].xAxis[0].categories;
categories.push(temp_round_id);
charts[0].xAxis[0].setCategories(categories, false);
charts[0].redraw();
});
}
}

Why does this Highcharts graph only show tooltip for the first and last nodes?

I'm just starting out with Highcharts and I'm having a little trouble showing a tooltip for each data item in my graph. At the moment, it just shows a tooltip for the first and last item.
var chart1; // globally available
$(document).ready(function () {
var options = {
chart: {
renderTo: 'AssessmentChart',
marginRight: 100,
marginBottom: 40
},
title: {
text: 'Assessment history',
x: -20 //center
},
subtitle: {
text: 'Assessment history for this patient',
x: -20 //center
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Score'
},
max: 72,
min: 0
},
tooltip: {
formatter: function() {
return '<b>'+ this.y +'</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
// Get the main assessment data...
var dlqiData = [], hdnDlqiData = $("#hdnDlqiData");
if (hdnDlqiData.length > 0) {
var dlqiDataJson = $.parseJSON(hdnDlqiData.val());
$.each(dlqiDataJson, function (i, item) {
dlqiData.push(
{
x: stringToUtcDate(item.dateCreated),
y: item.calculatedScore
}
);
});
options.series.push({
type: 'spline',
name: 'DLQI',
data: dlqiData
});
}
chart1 = new Highcharts.Chart(options);
function stringToUtcDate(datestring) {
var date = datestring.split('/');
return Date.UTC(parseInt(date[2], 10), parseInt(date[1], 10) - 1, parseInt(date[0], 10));
}
});​
I'm pulling data in from a hidden form field, so here's a Fiddle showing this in action: http://jsfiddle.net/gfyans/LjRGk/3/
Here's one of the official Fiddle's, http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-basic/, and they manage it OK, but I can't see from that what I'm dong wrong/differently.
I know it'll be something insanely easy, but I can't see it. Can anyone point me in the right direction?
Thanks,
Greg.
You need to have your data in ascending date order if using a datetime x-axis.

how to add dynamic data in a highchart?

I have a Highchart that is receiving JSON data via AJAX and jQuery. But my chart doesn't show the points until I hover the mouse over the chart. Even then the points are all at the very top of the chart. I don't think I'm adding my points to the series correctly. Please tell me what I'm doing wrong in the jsonpcallback function.
Thanks!
<script type="text/javascript">
<!-- Begin Chart options-->
// define the options
var options = {
chart: {renderTo: 'container'},
title: {text: 'Brewery'},
subtitle: {text: ' '},
xAxis: {text: 'Time',type: 'datetime'},
yAxis: [{ // left y axis
title: {text: 'Temperature (℉)'},
labels: {align: 'left', x: 3, y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);}
},
showFirstLabel: false},
{ // right y axis
linkedTo: 0, gridLineWidth: 0, opposite: true,
title: {text: 'Temperature (℉)'},
labels: {align: 'right', x: -3, y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);}
},
showFirstLabel: false
}],
legend: {align: 'left', verticalAlign: 'top', y: 20,
floating: true, borderWidth: 0},
tooltip: {shared: true, crosshairs: true},
plotOptions: { series: {cursor: 'pointer',
point: {events: {
click: function() {
hs.htmlExpand(null, {
pageOrigin: {
x: this.pageX,
y: this.pageY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) +':<br/> '+
this.y +'(℉)',
width: 200});
}}},
marker: {lineWidth: 1}}},
series: [ {name: 'Hot Liqour Tank'},
{name: 'MashTun'},
{name: 'Brew Kettle'},
{name: 'Post Chiller'},
{name: 'Control Box'}
]
};
<!-- End Chart Options -->
var chart;
//after DOM is loaded setup timeout to call the ajax method
$(document).ready(function() {
//call function to render the chart and setup the options
renderChart();
});
//this function requests the data
function reqData(){
$.ajax({
url: "http://192.168.0.11/"+Math.random(),
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
}
function jsonpcallback(rtndata) {
for(var i = 0; i < rtndata.length; i++){
if(rtndata[i].sensor=="hlt")
{
chart.series[0].addPoint([rtndata[i].time, rtndata[i].temp]);
}
else if(rtndata[i].sensor=="mt")
{
chart.series[1].addPoint([rtndata[i].time, rtndata[i].temp]);
}
else if(rtndata[i].sensor=="bk")
{
chart.series[2].addPoint([rtndata[i].time, rtndata[i].temp]);
}
else if(rtndata[i].sensor=="pc")
{
chart.series[3].addPoint([rtndata[i].time, rtndata[i].temp]);
}
else if(rtndata[i].sensor=="box")
{
chart.series[4].addPoint([rtndata[i].time, rtndata[i].temp]);
}
}
}
function renderChart(){
chart = new Highcharts.Chart(options);
}
//continually poll for data
setInterval(reqData, 5000);
</script>
I think you are nearly there; the only piece i believe you are missing is an initial call to your regData function from the chart's load event.
So to your second line after define the options, change this line:
chart: {renderTo: 'container'},
to this:
chart: {renderTo: 'container', events: {load: regData}},
Try converting the time strings to Javascript datetime objects. Highcharts will then read the datetimes correctly. For example, if the JSON date is in the format 'YYYY-MM-DD' you can use this code:
var dates = [];
$.each(jsondata[0], function(itemNo, item) {
year = parseInt(item.split('-')[0], 10);
month = parseInt(item.split('-')[1], 10);
day = parseInt(item.split('-')[2], 10);
dt = Date.UTC(parseInt(year), parseInt(month), parseInt(day));
series[0].data.push([dt, parseInt(jsondata[2][itemNo], 10)]);
series[1].data.push([dt, parseInt(jsondata[1][itemNo], 10)]);
dates.push(dt);
});
options.series = series;

Categories

Resources