Highcharts Displaying same data repeatedly - javascript

Thought I'd ask for a hand in this, am currently trying to code up a highcharts javascript file to display some data I have. I have been able to display the correct number of data sets, and on the correct graphs (they go into a time or proc graph) but I have an issue where ALL the graphs are using the same name & data, regardless of which graph they are on as well. Even though when i do an alert on where they are being assigned to their object arrays, they are all individual. Really unsure of what is happening.
where an Obj is:
{
name: SERIES_NAME,
data: SERIES_DATA,
}
The output graphs, instead of having the data as follows:
Graph Data: { Obj1, Obj2, Obj3...ObjN }, Showing multiple individual series.
I have:
Graph Data: { ObjN, ObjN, ObjN...ObjN },
They are all just ObjN. Even across the two graphs. All the data/names are the same.
Also all of this code is called from within a php $(document).ready(function())
function create_highchart(TIER,ARRAYS_STRING) {
var chart;
timestamp=document.getElementById("TIMESTAMP").value;
var graph_dir = "graphs/capsim/"+timestamp+"/";
var glue_outer = "___";
var glue_inner = ":#:";
var glue_csv="^";
var i = 0;
var j = 0;
var tier_names=[];
var WL_names = [];
var CSV_data=[];
var CSVs = [];
var CSV_det=[];
var out_arrays=[];
var time_ids = ['queue','util','arrival','thruput'];
out_arrays = ARRAYS_STRING.split(glue_outer);
tier_names = out_arrays[0].split(glue_inner);
WL_names = out_arrays[1].split(glue_inner);
CSVs = out_arrays[2].split(glue_inner);
CSV_det = out_arrays[3].split(glue_inner);
WL_num = WL_names.length;
tier_names.push('Overall System');
tier_max = tier_names.length;
curr_tier_name = tier_names[TIER];
while(i<CSVs.length){
CSV_data[i]=[];
data = CSVs[i].split(glue_csv);
CSV_data[i]=data;
i=i+1;
}
i=0;
var TMP_series = {
name: '',
data: [],
}
var TIME_SERIES_DATA=[];
var PROC_SERIES_DATA=[];
var time_count=0;
var proc_count=0;
var x = [];
var y = [];
var cat = [];
var out2 = [];
var options_time={
chart: {
renderTo: 'hc_div2',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: TIME_SERIES_DATA
};
var options_proc={
chart: {
renderTo: 'hc_div1',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: PROC_SERIES_DATA
};
var i=0;
if(TIER==tier_max-1){
TIER='OVR';
};
while(i<=CSV_det.length){
csv = CSV_det[i+4];
curr_data=CSV_data[(i/5)];
csv_name = CSV_det[i+1];
csv_tier = CSV_det[i+2];
csv_wl = parseFloat(CSV_det[i+3])+1;
wl_info = '';
if(CSV_det[i+3] !='NA'){
wl_info = ' Workload: '+csv_wl;
};
var j=0;
var line = '';
if(TIER==csv_tier){
TMP_series.data = [];
TMP_series.name = csv_name+wl_info;
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
i=i+5;
};
var chart = new Highcharts.Chart(options_proc);
var chart = new Highcharts.Chart(options_time);
}
A quick explanation on whats going on:
Initially parsing all the data into relevant bins from the arrays string
Creating the two highcharts that wil be displayed
Scanning over the CSVs to find ones that are relevant
For ones that are, reading their Data, and adding it to a TMP_series
Once all data is read, adding the TMP_series to the relevant graph data series
Any help is greatly apprecaited!
Thanks

You need to reset TMP_series to a new object each time you generate a series. Right now you are recycling the same object, and pushing references to the same object into the series arrays. Modify the last bit of your code to read like this:
if(TIER==csv_tier){
TMP_series = {
name : csv_name+wl_info,
data : []
};
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
Notice how at the top of the if, I create a new object with the specified properties, and assign it to the reference TMP_series. Remember, objects are passed by reference, so when you push objects into arrays, you are pushing a reference to the object, not a copy of the object.

Related

How to update Highcharts data dynamically over a period of time

I want to use Highcharts graph and update y axis dynamically. Actually I want to update nsw, Tas, ACT every 5 sec. How do I do it ?
Here is my code.
$(function () {
$('#container').highcharts({
title: {
text: 'Histogram',
x: -20 // center
},
subtitle: {
text: 'Source: www.trove.com',
x: -20
},
xAxis: {
categories: ['NSW', 'Tas', 'ACT','QLD','VIC','SA','WA']
},
yAxis: {
title: {
text: 'Hits'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'States',
data: [nsw, Tas, ACT,qld,vic,sa,wa]
}]
});
});
});
In the Documentation you can find an example from Highcharts in jsfiddle. Check it out http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/dynamic-update/. In the example every second a new point will be added. Here comes the relevant code part:
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
`
The easiest way to do it would be to use the javascript function "setInterval()" to call it.
Here is a link where you can find a way to do it :
http://www.w3schools.com/js/js_timing.asp
If you are not really good at javascript, you might need this declaration of functions : var functionName = function() {} vs function functionName() {}
Use:
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random(),
l = series.data.length;
for(var i = 0; i < l; i++) {
series.data[i].update({
y: getHits(i) // or something else
});
}
}, 5000); // 5 seconds
}
}
Where index is index (count from 0) of nsw/Tas/ACT in data array. (for nsw = 0, for Tas = 1 etc.)

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

Create Line in Highcharts with start and end point

Please look at following example:
<script type="text/javascript">
var $j = jQuery.noConflict();
function recalculateUTCValue(startingUTC, add) {
zeit = new Date(startingUTC);
zeit.setDate(zeit.getDate()+add);
return zeit;
}
function calcDateFromUTC(utc) {
d = new Date(utc);
return d;
}
function getDaysUntilEnd(utc) {
var currentTime = new Date();
var endTime = calcDateFromUTC(utc);
var diff = Math.floor(( Date.parse(endTime) - Date.parse(currentTime) ) / 86400000);
return diff;
}
</script>
<script type="text/javascript">
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
var TaskChart; // Chart-Objekt
var container = $j('#chart01')[0];
var TaskDuration = new Array();
var startingKW = 298;
// Save starting points to javascript variables for HighCharts
var startingUTC = 1288087223364;
// For a given time point id
var startTimePoint = 0;
var endTimePoint = 0;
TaskDuration = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0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,171.0,149.0,160.5,160.5,160.5];
// Get first value which is not "0"
var firstValue = 0;
for(var i = 0; i < TaskDuration.length; i++) {
if(TaskDuration[i] != 0) {
firstValue = i;
break;
}
}
// Get largest Y-Value; need for automatically zooming (setExtremes method)
var largest = Math.max.apply(Math, TaskDuration);
var myStartDate;
var myEndDate;
// Check if we have a time point in the query
if(startTimePoint != 0) {
var myStartDate = calcDateFromUTC(startTimePoint);
var myEndDate = calcDateFromUTC(endTimePoint);
} else {
// Otherwise we use the time of first created work item
var myStartDate = recalculateUTCValue(startingUTC, firstValue);
var myEndDate = new Date();
}
</script>
<script type="text/javascript">
$j(document).ready(function() {
TaskChart = new Highcharts.Chart({
credits: {
enabled: false
},
chart: {
renderTo: "chart01",
defaultSeriesType: 'line',
zoomType: 'x',
events: {
load: function(event) {
this.xAxis[0].setExtremes(myStartDate, myEndDate);
this.yAxis[0].setExtremes(0,largest);
}
}
},
title: {
text: "Task Burn Down Chart"
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
week: '%e. %b %Y'
},
labels: {
align: 'right',
rotation: -60,
x: 5,
y: 15
},
offset: 10
},
yAxis: {
title: {
text: "Number of Hours"
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>' + Highcharts.dateFormat('%d.%m', this.x) +': '+ this.y;;
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
}
},
series: [
{
name: 'Hours',
pointStart: startingUTC,
pointInterval: 24*60*60*1000,
data: TaskDuration
},
{
type: 'line',
name: 'Regression Line',
data: [[myStartDate, 216], [myEndDate, 50]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}]
});
});
</script>
http://jsfiddle.net/JwmuT/8/
The goal is to create a Highchart line with starting point from X-Value 26th January and with the end point on the X-Value 7th February. Corresponding Y-Values are "260" and "0".
How to create a simple line with these to points in HighCharts? Maybe Highcharts is able to do a linear regression on the fly?!
I have found this demo but I do not know how to pass correctly X-Values in the Date format.
Highcharts doesn't calculate any type of regression or trend lines. In example you have posted, data is calculated before, and Highcharts just displays that. However there is known plugin for trendline: https://github.com/virtualstaticvoid/highcharts_trendline

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.

Highcharts -- Array not assigned without alert message

Trying to get some help with this weird behavior.
I managed to get the highcharts chart, multiple series etc. all setup. When using static values from a inline array, the values are assigned correctly to the chart, but if I pull the numbers out of a csv file, they are not assigned unless I pause execution with an alert message. Please see code below
$(function () {
// every row on report needs
// category defined (left side)
var mycategories = [];
// every column on report needs
// seriesname defined
var headers = [];
var myseriesnames = [];
var lines = [];
var line_tokens = [];
// Read data from csv file
$.get('top10raj.csv', function(data) {
// Split the lines
lines = data.split('\n');
console.log("First line : "+ lines[0]);
headers = lines[0].split(',');
for (var i = 1; i < headers.length; i++) {
myseriesnames.push(headers[i]);
}
//
// display all lines
//
for (var i = 1; i < lines.length; i++) {
line_tokens = lines[i].split(',');
console.log('Equip.No:' + line_tokens[0].trim()); // Equipment Number
console.log(line_tokens[1].trim()); // ActualCost
console.log(line_tokens[2].trim()); // ActualMaterial
console.log(line_tokens[3].trim()); // ActualLabor
console.log(line_tokens[4].trim()); // ActualOther
mycategories.push(line_tokens[0].trim());
}
});
alert('report ready');
var myarray = [7,6,7,8,7,8,3,4,1,4,7,8,7,5];
var serObj = [{ 'name': myseriesnames[0],
data:[8,9,8,6,5,2,3,6,5,7,4,5,8,9]
},
{ 'name': myseriesnames[1],
data:[8,5,6,9,8,7,4,5,2,5,8,7,8,6]
},
{ 'name': myseriesnames[2],
data: myarray
},
{ 'name': myseriesnames[3],
data: myarray
},
];
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
type: 'column'
},
title:{
text:'Chart Title'
},
tooltip:{
formatter:function(){
return '<b>' + this.series.name + '</b>' +
'<br/><b>Item Number:</b> ' + this.x + // X Value
'<br/><b>Amount:</b> ' + this.y + // Y Value
'<br/><b>Other Data:</b> ';// + this.point.note;
}
},
credits:{enabled:false},
legend:{
},
plotOptions: {
series: {
shadow:false,
borderWidth:0
}
},
xAxis:{
// Need to define categories for every row
// on the report (left side)
categories: mycategories,
lineColor:'#999',
lineWidth:1,
tickColor:'#666',
tickLength:3,
labels: { rotation:45, align:'left'},
title:{
text:'Equipment',
}
},
yAxis:{
lineColor:'#999',
lineWidth:1,
tickColor:'#666',
tickWidth:1,
tickLength:3,
gridLineColor:'#ddd',
title:{
text:'Amount (USD)',
rotation:-90,
margin:50,
}
},
series: serObj
});
});
EqptNumber,ActualTotal,ActualMaterial,ActualLabor,ActualOther,
111.3207B,666693.61,606564.37,53866.49,6262.75,
106.3355,588647.91,240175.91,322779.00,25693.00,
106.3307,364234.86,266598.36,97636.50,0,
125.L8702A,356025.49,347519.49,8506.00,0,
122.E8801A,340712.89,25483.39,33729.50,281500.00,
127.E2201,319372.29,112362.97,307731.88,100722.56,
107.3251A,310587.25,316225.36,35496.50,41134.61,
622.CW88105,307762.86,7957.36,299805.50,0,
133.1203A,307285.20,40273.19,249658.01,17354.00,
106.3352,278737.48,132009.49,146728.00,0.01,
107.3251ACC,310587.25,316225.36,35496.50,41134.61,
622.CW88105CC,307762.86,7957.36,299805.50,0,
133.1203ACC,307285.20,40273.19,249658.01,17354.00,
106.3352CC,278737.48,132009.49,146728.00,0.01,
The csv file I am using is shown at the bottom of the source.
if the following line
alert('report ready');
is commented out, I lose all the categories labels and they are replaced by 0..1,2,3.. etc. along the X-Axis. Trying hard to understand why this is happening, but so far no luck in fixing. Appreciate any help I can get with this, as I really want to use the Highcharts library with dynamic data and using only static data from predefined arrays is very limiting.
The problem is that your request for the csv file ($.get ) is executed asynchronously, meaning that the rest of your code is running before the data is returned. Try moving your code into the callback function, something like
//..your code
mycategories.push(line_tokens[0].trim());
}
//moved your code here
var myarray = [7,6,7,8,7,8,3,4,1,4,7,8,7,5];
var serObj = [{ 'name': myseriesnames[0],
data:[8,9,8,6,5,2,3,6,5,7,4,5,8,9]
},
{ 'name': myseriesnames[1],
data:[8,5,6,9,8,7,4,5,2,5,8,7,8,6]
},
{ 'name': myseriesnames[2],
data: myarray
},
{ 'name': myseriesnames[3],
data: myarray
},
];
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
type: 'column'
},
title:{
text:'Chart Title'
},
tooltip:{
formatter:function(){
return '<b>' + this.series.name + '</b>' +
'<br/><b>Item Number:</b> ' + this.x + // X Value
'<br/><b>Amount:</b> ' + this.y + // Y Value
'<br/><b>Other Data:</b> ';// + this.point.note;
}
},
credits:{enabled:false},
legend:{
},
plotOptions: {
series: {
shadow:false,
borderWidth:0
}
},
xAxis:{
// Need to define categories for every row
// on the report (left side)
categories: mycategories,
lineColor:'#999',
lineWidth:1,
tickColor:'#666',
tickLength:3,
labels: { rotation:45, align:'left'},
title:{
text:'Equipment',
}
},
yAxis:{
lineColor:'#999',
lineWidth:1,
tickColor:'#666',
tickWidth:1,
tickLength:3,
gridLineColor:'#ddd',
title:{
text:'Amount (USD)',
rotation:-90,
margin:50,
}
},
series: serObj
});
});
//here's where the alert used to be
///alert('report ready');
});

Categories

Resources