JavaScript - Highcharts box plot not displaying - javascript

I am having trouble creating a highcharts box-plot graph, I have all the data in the correct format i.e. min, lower quartile, median, upper quartile and max.
I can display the categories but I cannot get it to display the data.
This is my code:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
a: final[i].p20,
b: ((final[i].p30 + final[i].p40) / 2),
c: ((final[i].p50 + final[i].p60) / 2),
d: ((final[i].p70 + final[i].p80) / 2),
e: final[i].p90,
});
}
console.log(formated)
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: 'Highcharts Box Plot'
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Values',
data: formated,
tooltip: {
headerFormat: '<em>Till No. {point.key}</em><br/>'
}
}]
});
}
This is an example of the formatted array and the data it contains:
This is how the graph currently looks, you can see the categories array is working but it is not showing the data:

I was able to solve this by changing how I gathered the data, Im not sure if the box plot is case sensitive but by changing the variable names the data displayed
This is the whole code I am using:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
var heading = #Html.Raw(Json.Encode(#ViewBag.QueryTitle));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
low: final[i].p20,
q1: ((final[i].p30 + final[i].p40) / 2),
median: ((final[i].p50 + final[i].p60) / 2),
q3: ((final[i].p70 + final[i].p80) / 2),
high: final[i].p90,
});
}
console.log(formated)
var boxData = [];
//boxData.push(formated);
//console.log(boxData);
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: heading
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Distribution'
}
},
series: [{
name: 'Tills',
data:
formated
}]
});
}

Related

Highcharts Remote Data - JSON Object Undefined

I'm trying to render a Highcharts column chart from MySQL data -> json_encode() -> getJSON(). 95% of the time there are 6 rows of data to process, so this can be easily looped through manually and the chart renders fine. The problem is when there are occasionally fewer rows in the results array - I am of course seeing TypeError: Cannot read property 'name' of undefined in these cases.
My working code:
$.getJSON(url, function(json)) {
if(typeof json === 'object' && json.length > 0) {
var nameData = [json[0]['name'],json[1]['name'],json[2]['name'],json[3]['name'],json[4]['name'],json[5]['name']];
var matchedData = [json[0]['data']['Matched'],json[1]['data']['Matched'],json[2]['data']['Matched'],json[3]['data']['Matched'],json[4]['data']['Matched'],json[5]['data']['Matched']];
var bookedData = [json[0]['data']['Booked'],json[1]['data']['Booked'],json[2]['data']['Booked'],json[3]['data']['Booked'],json[4]['data']['Booked'],json[5]['data']['Booked']];
}
var options = {
chart: {
renderTo: 'div',
type: 'column'
},
title: {
text: 'Chart Title',
x: -20
},
xAxis: {
type: 'category',
categories: nameData,
crosshair: true
},
series: [{
name: 'Matched',
data: matchedData
}, {
name: 'Booked',
data: bookedData
}]
}
chart = new Highcharts.Chart(options);
}
This renders the chart correctly. However when there are fewer than the usual 6 items in the array, the TypeError stops things.
I attempted this to count the array items prior to sending to Highcharts:
var nameData = [];
var matchedData = [];
var bookedData = [];
if (typeof json === 'object' && json.length > 0) {
for (var a = 0; a < json.length; a++) {
nameData += [json[a]['name']+","];
matchedData += [json[a]['data']['Matched']+","];
bookedData += [json[a]['data']['Booked']+","];
}
}
This alerts() out the same results as the manually-created array, but nothing renders on the chart. What needs to change?
Try mapping over your data. You can set everything really easily using the map function. It's a lot cleaner and simpler as well. You can find a reference for map here.
$.getJSON(url, function(json)) {
if(typeof json === 'object' && json.length > 0) {
var nameData = json.map(obj => obj['name']);
var matchedData = json.map(obj => obj['data']['Matched']);
var bookedData = json.map(obj => obj['data']['Booked']);
}
var options = {
chart: {
renderTo: 'div',
type: 'column'
},
title: {
text: 'Chart Title',
x: -20
},
xAxis: {
type: 'category',
categories: nameData,
crosshair: true
},
series: [{
name: 'Matched',
data: matchedData
}, {
name: 'Booked',
data: bookedData
}]
}
chart = new Highcharts.Chart(options);
}

HighChart - accessing series data by category name

The question is simple. How do I programmatically edit data series which corresponds to desired_category_name in this Fiddle ?
$(function() {
var chart, x,
btnRemove = $('#remove'),
btnAdd = $('#add'),
btnEdit = $('#edit');
x = 10;
btnAdd.click(function() {
chart.series[0].addPoint(Math.floor(Math.random() * 10 + 1)); // Return random integer between 1 and 10.
});
btnEdit.click(function() {
desired_category_name = 'USA'
// Do something like chart.series[0].data[i].update(x += 10);
});
btnRemove.click(function() {
if (chart.series[0].points[0]) {
chart.series[0].points[0].remove();
}
});
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'No data in pie chart'
},
series: [{
type: 'pie',
name: 'Random data',
data: [
['USA', 1],
['Europe', 2]
]
}]
});
chart = $('#container').highcharts();
});
You can access series data with this - it has an array of points:
chart.series[0]
You can modify point with this:
chart.series[0].data[0].update( _new_value_ )
Each point has an attribute "name" that corresponds to category.
chart.series[0].data[0].name // USA
http://jsfiddle.net/3nhm9cjc/
$('#edit').click(function() {
desired_category_name = 'USA';
// Do something like chart.series[0].data[i].update(x += 10);
console.log(chart.series[0].data.length)
for(var i = 0; i< chart.series[0].data.length; i++){
if(chart.series[0].data[i].name===desired_category_name){
chart.series[0].data[i].update(10);
}
}
});

highcharts-ng ajax data load

I have the following HTTP request that i use to fill out my chart:
$scope.series = ['Moduler tager', 'Gns.score'];
$scope.activity_data = [];
$scope.activity_ticks = [];
var tmp_data = [];
$scope.bar = [];
$scope.line = [];
$http.get(api.getUrl('findSelfActivityByDivisions', null))
.success(function (response) {
response.forEach(function(y){
var i = 0;
var log_date = y.date.substr(0, y.date.indexOf('T'));
var date = new Date(log_date);
var logg_date = moment(date).fromNow();
var indexOf = tmp_data.indexOf(logg_date);
var found = false;
var index = 0;
if(tmp_data.length > 0){
tmp_data.forEach(function(current_data){
if(current_data[0] == logg_date){
found = true;
}
if(!found){
index++;
}
})
}
if(found){
var tmp = tmp_data[index];
tmp[1] = tmp[1] + y.num_modules;
tmp[2] = tmp[2] + y.num_score_modules;
tmp[3] = tmp[3] + y.sum_score;
tmp_data[index] = tmp;
}
else
{
var tmp = [logg_date, y.num_modules, y.num_score_modules, y.sum_score];
tmp_data.push(tmp);
}
})
var line = [];
var bar = [];
tmp_data.forEach(function(data){
$scope.activity_ticks.push(data[0])
line.push(data[1]);
var avg_score = data[3] / data[2];
if(isNaN(avg_score)){
avg_score = 0;
}
bar.push(avg_score);
});
$scope.line = line;
$scope.bar = bar;
});
Now then i have the following chart config:
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
Sadly none of the graphs are showing (im guessing it has something to do with the date comming after the load)
Can anyone help me out?
Your $scope.chartConfig is likely firing before the success callback of your $http.get(api.getUrl('findSelfActivityByDivisions', null)) completes. I am assuming $scope.chartConfig is located in a controller. Try placing a $watchGroup on the values then apply your chart rendering logic once those values resolve. An example may include
Note that $watchGroup is found within Angular as of 1.3
$scope.$watchGroup(['line', 'bar'], function(newValues, oldValues) {
// newValues[0] --> $scope.line
// newValues[1] --> $scope.bar
if(newValues !== oldValues) {
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
}
});

Update Highchart data form exported button

I'm trying to use the exporting option to add a button which is then used to switch between a line chart with the real point and another with the cumulative sum of them.
I'm using the following code:
$(function () {
$('#container').highcharts({
chart: {
type: 'line'
},
xAxis: {
tickPixelInterval: 200,
categories: jsonResponse["Date"]
},
series: {
data: jsonResponse["values"]
},
exporting: {
buttons: {
'myButton': {
_id: 'myButton',
symbol: 'diamond',
text: 'Cumulative',
x: -62,
symbolFill: '#B5C9DF',
hoverSymbolFill: '#779ABF',
onclick: function() {
if(!cumulative){
this.series[0].setData = cumcum(jsonResponse["values"]);
alert(this.series[1].setData);
cumulative = true;
} else {
this.series[0].setData = jsonResponse["values"];
cumulative = false;
alert(this.series[1].setData);
}
},
_titleKey: "myButtonTitle"
}
}
}
});
});
function cumcum(data){
var res = new Array();
res[0] = data[0];
for(var i=1; i<data.length; i++) {
res[i] = res[i-1] + data[i];
}
return res;
}
From the alert I can see that the data are correctly calculated but the plot stays the same.
I also tried series[0].yData and series[0].processedYData
setData is a function, you have to call it like:
this.series[0].setData(cumcum(jsonResponse["values"])
See API http://api.highcharts.com/highstock#Series for more information.

Highcharts Displaying same data repeatedly

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.

Categories

Resources