Binding Highcharts Pie Chart to differently formatted data - javascript

I have a pie chart integration in Spotfire which works well when the data is in a simpler format in 'data' and 'columns'. The data binds to the chart properly (this is the kind of format i've seen in most demos).
However in other real-life usages in Spotfire, the JSON which is produced is differently formatted and ceases to draw a pie chart properly. I think it should be possible to adjust the script to bind to this data format, but i don't know how?
In my fiddle it is working with simpler data format, if commenting this out and uncommenting the other data the failed chart can be seen...
https://jsfiddle.net/paulsmithleadershipfactor/3k2gzuw0/
The full code is here also...
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9"/>
<title>JS Visualization Tester with Highcharts</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script>
var chart; // Global chart object used to determine whether Highcharts has been intialized
var color = null;
var pie = null;
var svg = null;
var path = null;
function renderCore(sfdata)
{
if (resizing) {
return;
}
// Extract the columns
var columns = sfdata.columns;
columns.shift();
// Extract the data array section
var chartdata = sfdata.data;
// count the marked rows in the data set, needed later for marking rendering logic
var markedRows = 0;
for (var i = 0; i < chartdata.length; i++)
{
if (chartdata[i].hints.marked)
{
markedRows = markedRows + 1;
}
}
var width = window.innerWidth;
var height = window.innerHeight;
var radius = Math.min(width, height) / 2;
if ( !chart )
{
$('#js_chart').highcharts({
chart: {
plotBackgroundColor: '#f1f2f2',
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Pie',
},
tooltip: {
formatter: function() {
var sliceIndex = this.point.index;
var sliceName = this.series.chart.axes[0].categories[sliceIndex];
return sliceName + ':' +
'<b>' + this.y + '</b>';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
showInLegend: true,
depth: 35,
innerSize: 100,
dataLabels: {
enabled: true,
format: '{point.y:,.0f}'
}
}
},
legend: {
enabled: true,
labelFormatter: function() {
var legendIndex = this.index;
var legendName = this.series.chart.axes[0].categories[legendIndex];
return legendName;
}
},
xAxis: {
categories: columns
}
});
}
chart = $('#js_chart').highcharts();
for ( var nIndex = 0 ; nIndex < chartdata.length ; nIndex++ )
{
var row = chartdata[nIndex];
// Check for an existing chart data series with the current id
var series = chart.get ( row.items[0] );
var seriesData = [];
for (var c = 1; c < row.items.length; c++) {
seriesData.push(Number(row.items[c]));
}
if ( series != null )
{
// Update the existing series with the new data
series.update ( {
data: seriesData
}, false );
}
else
{
// Create a new series
chart.addSeries ( {
id: row.items[0],
name: row.items[0],
data: seriesData
}, false );
}
}
for ( nSeriesIndex = 0 ; nSeriesIndex < chart.series.length ; nSeriesIndex++ )
{
var series = chart.series[nSeriesIndex];
var found = false;
for ( nDataIndex = 0 ; nDataIndex < chartdata.length ; nDataIndex++ )
{
var row = chartdata[nDataIndex];
if ( series.name == row.items[0] )
{
found = true;
break;
}
}
if ( found != true )
{
series.remove ( false );
nSeriesIndex = 0;
}
}
chart.redraw ();
wait ( sfdata.wait, sfdata.static );
}
var resizing = false;
window.onresize = function (event) {
resizing = true;
if ($("#js_chart")) {
}
resizing = false;
}
</script>
</head>
<body>
<button style="position:absolute; z-index:99" type="button" onclick="call_renderCore()">Call renderCore</button>
<div id="js_chart"></div>
<script type="text/javascript">
function call_renderCore()
{
var sfdata =
{
"columns": ["Sales (Total)", "Marketing (Total)", "Development (Total)", "Customer Support (Total)", "IT (Total)", "Administration (Total)"],
/* comment out the 'columns' above and uncomment 'columns' below */
/* "columns": [
"count([lastcontact])",
"First([lastcontact])"
], */
/* uncomment above and comment below */
"data": [{"items": [93000, 58000, 102000, 66000, 43000, 24000], "hints": {"index": 0}}]
/* comment out the 'data' above and uncomment 'data' below */
/* "data": [
{
"items": [
131,
"3 – 6 months"
],
"hints": {
"index": 0
}
},
{
"items": [
78,
"6 months – 1 year"
],
"hints": {
"index": 1
}
},
{
"items": [
89,
"Can't remember"
],
"hints": {
"index": 2
}
},
{
"items": [
56,
"Over a year ago"
],
"hints": {
"index": 4
}
},
{
"items": [
442,
"Less than 3 months"
],
"hints": {
"index": 3
}
}
], */
}
renderCore ( sfdata );
display_data ( sfdata );
}
</script>
</body>
</html>

Related

Why highchart returning " Typeerror : undefined variable byte "?

I am trying to draw a graph with the help of high chart and also using load event I am trying to add values after each 1 second to the graph.
In this graph I also want to show axis as Mb,Kb,,Gb data. So I am writing a function to return the byte values as Mb,Kb,Gb (for both series and tooltip)
This is my code :
// highchart options :
var series1, series2 ;
var chart = {
type: 'bar',
events: {
load: function () {
// set up the updating of the chart each second
series1 = this.series[0];
series2 = this.series[1];
setInterval(function () {
add_function();
}, 1000);//call function each 1 second
}
}
};
var tooltip = {
enabled: true,
formatter: function() { return fbytes(this.y,2);}
};
var plotOptions = {
bar: {
},
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
pointPadding: 0,
pointWidth:38
},
column : {
grouping: true
}
};
series= [
{
name: 'old',
color: '#f9a80e',
data: [,]
},
{
name: 'new',
color: '#89897f',
data: [,]
}
];
and the load event function is :
Array.max = function (array) {
return Math.max.apply(Math, array);
};
Array.min = function (array) {
return Math.min.apply(Math, array);
};
add_function()
{
var arr[];
//getting array values here
var min_value = Array.min(arr);
var max_value = Array.max(arr);
var chart2 = $('#container').highcharts();
chart2.yAxis[0].update({max:max_value, min: 0}, true);
series1.setData([arr[0],arr[2]], true, true);
series2.setData([arr[1],arr[3]], true, true);
}
and the conversion function :
function fbytes(bytes, precision) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var posttxt = 0;
if (bytes == 0) return '0 Bytes';
if (bytes < 1024) {
return Number(bytes) + " " + sizes[posttxt];
}
while( bytes >= 1024 ) {
posttxt++;
bytes = bytes / 1024;
}
return Math.round(bytes.toPrecision(precision)) + " " + sizes[posttxt];
}
my logic : i got some array values randomly and i am displaying this data on the graph .
problem facing : I didn't get this.y value inside series . When i print this value inside
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
I am getting this.y = undefined . What is happening ?
Any mistake in the code ? Any suggestions ?
I created demo using your code and modified add_function() a little bit. Did you mean something like this?
function add_function(series1, series2) {
var chart2 = $('#container').highcharts(),
increment = 1024,
min_value,
max_value,
newVal1 = [],
newVal2 = [];
if (!series1.data.length && !series2.data.length) {
var arr = [512, 128, 1024, 0];
min_value = Array.min(arr);
max_value = Array.max(arr);
newVal1 = [arr[0], arr[2]];
newVal2 = [arr[1], arr[3]];
} else {
series1.yData.forEach(function(sEl, sInx) {
newVal1.push(sEl + increment);
});
series2.yData.forEach(function(sEl, sInx) {
newVal2.push(sEl + increment);
});
max_value = Array.max(newVal1.concat(newVal2));
}
chart2.yAxis[0].update({
max: max_value,
min: 0
}, true);
series1.setData(newVal1, true, true);
series2.setData(newVal2, true, true);
}
Example:
http://jsfiddle.net/js3g311q/

HighStock Multiple series from CSV file (Arduino Based & JavaScript)

Ok hello everyone. I have designed my HighStock works from
CSV-file. I can get time and 1 line to my serie. I want to
get 2 lines from data. Any ideas? In future I want to get 2 decimals for example 25,01. have you got ideas for that?
In CSV there's seconds,data,data. And it's prints it 1minutes.
And yes, I'm from Finland Student and my code sucks... :)
http://imgur.com/L2VSRGj
Data:
Time in Seconds,Value,Value
0,25,23
60,25,23
120,25,23
....
14220,24,22
14280,24,22
14340,24,22
Javascript in my HC.htm: (it's index)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hannun virtamittaus</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
function getDataFilename(str){
point = str.lastIndexOf("file=")+4;
tempString = str.substring(point+1,str.length)
if (tempString.indexOf("&") == -1){
return(tempString);
}
else{
return tempString.substring(0,tempString.indexOf("&"));
}
}
query = window.location.search;
var dataFilePath = "/data/"+getDataFilename(query);
$(function () {
var chart;
$(document).ready(function() {
// define the options
var options = {
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 5
},
title: {
text: 'Arduinolla mitatut virran arvot'
},
subtitle: {
text: 'Zoomaa haluttu luenta alue'
},
xAxis: {
type: 'datetime',
maxZoom: 2 * 4000000
},
yAxis: {
title: {
text: 'Virran arvot 0-250A'
},
min: 0,
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%H:%M - %b %e, %Y', this.x) +': '+ this.y;
}
},
plotOptions: {
series: {
cursor: 'pointer',
lineWidth: 1.0,
point: {
events: {
click: function() {
hs.htmlExpand(null, {
pageOrigin: {
x: this.pageX,
y: this.pageY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%H:%M - %b %e, %Y', this.x) +':<br/> '+
this.y,
width: 100
});
}
}
},
}
},
series: [{
name: 'Op1',
marker: {
radius: 2
}
}]
};
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
// http://api.jquery.com/jQuery.get/
jQuery.get(dataFilePath, null, function(csv, state, xhr) {
var lines = [],
date,
// set up the two data series
lightLevels = [];
// inconsistency
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
// split the data return into lines and parse them
csv = csv.split(/\n/g);
jQuery.each(csv, function(i, line) {
// all data lines start with a double quote
line = line.split(',');
date = parseInt(line[0], 10)*1400;
lightLevels.push([
date,
parseInt(line[1], 10)
]);
});
options.series[0].data = lightLevels;
chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/4.2.4/highstock.js"></script>
<script src="https://code.highcharts.com/stock/4.2.4/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 155px"></div>
</body>
</html>
You need to set an array of series objects.
Series:
series: [{
name: 'Op1',
marker: {
radius: 2
}
},{
name: 'Op2'
}]
Parser
jQuery.get(dataFilePath, null, function(csv, state, xhr) {
var lines = [],
date,
// set up the two data series
lightLevels = [];
topLevels = [];
// inconsistency
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
// split the data return into lines and parse them
csv = csv.split(/\n/g);
jQuery.each(csv, function(i, line) {
// all data lines start with a double quote
line = line.split(',');
date = parseInt(line[0], 10)*1400;
lightLevels.push([
date,
parseInt(line[1], 10)
]);
topLevels.push([
date,
parseInt(line[2], 10)
]);
});
options.series[0].data = lightLevels;
options.series[1].data = topLevels;
chart = new Highcharts.Chart(options);
});

How to improve performance of Highcharts and avoid error 15 inspite of sorted data?

I am trying to create a gantt chart representation in highcharts with navigator. I get a JSON response from server (below is a typical response strucutre). In order to create a gantt chart representation I am creating a line between 2 points. Each point has a start_date and end_date and inorder to create this representation I am plotting a line between start_date and end_date of each point (which I have accomplished).
Response Structure from server
{
"took": 312,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 4115,
"max_score": 1,
"hits": [
]
},
"aggregations": {
"top-tags": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Process1",
"doc_count": 6,
"process": {
"value": {
"1449878649000": {
"start_date": 1449878649000,
"process_initiator": "lol#surg.com",
"end_date": 1449878734000,
"total_seconds": 85
},
"1449879753000": {
"start_date": 1449879753000,
"process_initiator": "lol#surg.com",
"end_date": 1449879850000,
"total_seconds": 97
},
"1449881550000": {
"start_date": 1449881550000,
"process_initiator": "lol#surg.com",
"end_date": 1449881631000,
"total_seconds": 81
}
}
}
},
{
"key": "Process2",
"doc_count": 1,
"process": {
"value": {
"1449971262000": {
"start_date": 1449971262000,
"process_initiator": "lol#surg.com",
"end_date": 1449971266000,
"total_seconds": 4
}
}
}
}
]
}
}
}
Code also sharing a plunker demo
var app = angular.module('app', []);
app.directive('operationalhighstackstock', function() {
return {
restrict: 'E',
scope: true,
link: function postLink(scope, element, attrs) {
scope.$watch('operationHighChartsData', function(values) {
new Highcharts.StockChart(values);
});
}
};
});
//2014-11-30T18:15:25.000-08:00
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.excludeValue = {
data: 0
};
$scope.isExcludeNeeded = true;
var opExcludeMinutes = 1,
AGENT_NAMES = "agent_names",
colorCodes = ["#8CC051", "#967BDC", "#5D9CEC", "#FB6E52", "#EC87BF", "#46CEAD", "#FFCE55", "#193441", "#193441", "#BEEB9F", "#E3DB9A", "#917A56"];
var setSummaryDisplay = function(e) {
if (e.min === null || e.max === null)
$scope.hideRangeSlider = true;
else
$scope.hideRangeSlider = false;
$scope.minimumSelectedValue = e.min;
$scope.maximumSelectedValue = e.max;
}
var getHichartsData = function(result) {
var tasksArr = [],
seriesArr = [],
userArr = [],
processArr = [];
var agentSeries = [],
agentData = {},
processSeries = [],
taskData = {},
idx = 0,
opProcessBucket = esResponse.aggregations["top-tags"].buckets,
seriesData = {};
var opBucketLength = opProcessBucket.length;
for (var opProcessBucketIndex = 0; opProcessBucketIndex < opBucketLength; ++opProcessBucketIndex) {
//opProcessBucket.forEach(function(processEntry) {
//if (opProcessBucket[opProcessBucketIndex]["key"] == $scope.gpDropDownTitle) {
var intervalBucket = opProcessBucket[opProcessBucketIndex]["process"]["value"], //opProcessBucket[opProcessBucketIndex]["top_tag_hits"]["hits"]["hits"],
intervalArr = [],
tasksIntervalArr = [],
opTaskidObj = {},
opTaskidIntervalObj = {},
process_name = null,
sortElementArr = [];
for (var key in intervalBucket) {
//intervalBucket.forEach(function(intervalEntry, intervalIndex) {
var intervalObj = {},
intervalObj2ndpoint = {},
processIntervalObj = {},
tintervalArr = [],
intervalIndex = 0,
start_temp = parseInt(key),
end_temp = intervalBucket[key].end_date; //start_temp = intervalBucket[key].start_date, end_temp = intervalBucket[key].end_date;
//added here since response contains null value and data load will take almost 1 date, verified with Bhavesh
$scope.currentDateTime = new Date().getTime();
if (end_temp == null)
end_temp = $scope.currentDateTime;
var st = new Date(moment(start_temp).valueOf()).getTime();
var et = new Date(moment(end_temp).valueOf()).getTime();
var duration = moment.duration(moment(et).diff(moment(st)));
var minutes = duration.asMinutes();
if (minutes > $scope.excludeValue.data && $scope.isExcludeNeeded) {
if (intervalIndex == 0 || process_name == null) {
process_name = opProcessBucket[opProcessBucketIndex]["key"];
processArr.push(opProcessBucket[opProcessBucketIndex]["key"]);
}
userArr.push(intervalBucket[key].process_initiator);
processIntervalObj["task_id"] = opProcessBucket[opProcessBucketIndex]["key"];
processIntervalObj["from"] = st;
var lFromtime = moment.utc(st).toDate();
lFromtime = moment(lFromtime).format('MM/DD/YY HH:mm');
var lTotime = moment.utc(et).toDate();
lTotime = moment(lTotime).format('MM/DD/YY HH:mm');
processIntervalObj["to"] = et;
processIntervalObj["color"] = "#FFCC4E";
processIntervalObj["fromDateString"] = lFromtime;
processIntervalObj["toDateString"] = lTotime;
processIntervalObj["process_initiator"] = intervalBucket[key].process_initiator == null ? 'Unknown' : intervalBucket[key].process_initiator;
processIntervalObj["total_seconds"] = intervalBucket[key].total_seconds;
//sortElementArr.push(intervalEntry["sort"][0]);
tasksIntervalArr.push(processIntervalObj);
}
}
opTaskidObj["name"] = process_name;
opTaskidIntervalObj["name"] = process_name;
opTaskidObj["data"] = [];
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
idx++;
if (tasksIntervalArr.length > 0) {
processSeries.push(opTaskidIntervalObj);
agentSeries.push(opTaskidObj);
}
//}
}
seriesData["title"] = "Test"; //item["key"];
var series = [];
(processSeries.reverse()).forEach(function(task, i) {
var item = {
name: task.name,
data: [],
turboThreshold: 1100000
};
(task.intervals).forEach(function(interval, j) {
item.data.push({
task_id: interval.task_id,
x: interval.from,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
}, {
task_id: interval.task_id,
x: interval.to,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
});
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
});
series.push(item);
})
seriesData["data"] = series;
seriesData["tasks"] = processSeries;
seriesArr.push(seriesData);
return seriesArr;
}
$scope.agentSeriesData = getHichartsData(esResponse);
var tasks = $scope.agentSeriesData[0].tasks;
var seriesData = $scope.agentSeriesData[0].data;
var xAxisStepping = 1 * 3600 * 1000;
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
height: 600,
events: {
load: function(e) {
var max = this.xAxis[0].max;
var range = (24 * 3600 * 1000) * 7; // one day * 7
if ($scope.isInit || $scope.filterReseted) {
$scope.filterReseted = false;
this.xAxis[0].setExtremes(max - range, max);
}
setSummaryDisplay.call(this.xAxis[0], {
trigger: "navigator",
min: this.xAxis[0].min,
max: this.xAxis[0].max
});
}
}
},
title: {},
credits: {
enabled: false
},
xAxis: {
type: 'datetime',
gridLineWidth: 1,
tickInterval: xAxisStepping,
//ordinal:false,
dateTimeLabelFormats: {
month: '%b %e, %Y'
},
events: {
afterSetExtremes: setSummaryDisplay
},
minRange: 1000
},
yAxis: {
tickInterval: 1,
gridLineWidth: 1,
labels: {
enabled: false,
formatter: function() {
if (tasks[this.value]) {
return tasks[this.value].name;
}
}
},
startOnTick: false,
endOnTick: false,
title: {
text: 'Process'
}
},
animation: false,
rangeSelector: {
enabled: false
},
navigator: {
enabled: true
},
legend: {
enabled: false
},
tooltip: {
shared: false,
formatter: function() {
var str = '';
str += 'Process: ' + this.series.name + '<br>';
str += 'From: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.from) + '<br>';
str += 'To: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.to) + '<br>';
return str;
}
},
plotOptions: {
line: {
lineWidth: 10,
marker: {
enabled: false
},
dataLabels: {
enabled: false,
borderRadius: 5,
borderWidth: 1,
y: -6,
formatter: function() {
return this.series.name;
}
},
states: {
hover: {
lineWidth: 10
}
}
},
series: {
cursor: 'pointer',
animation: false,
point: {
events: {
click: function() {
$scope.selectedGuide = this.series.name;
//$scope.showTableView();
}
}
},
turboThreshold: 100000000,
dataGrouping: {
enabled: false
}
}
},
scrollbar: {
enabled: false
},
series: seriesData
});
$scope.operationHighChartsData = chart;
}]);
I have sorted data (ascending order) but I am still getting Highcharts error #15: www.highcharts.com/errors/15 errors in thousands (mostly 80k +), which is hanging the browser.
What could be the issue and how can I get rid of it and increase performance? Sharing a plunker which has code and relatively small number of errors.
Note: I am using Highstock JS v2.1.5
There are two problems with this code:
First thing you need to sort the series in ascending order of X. I did not want to debug your code on how do you construct your data so I added a simple loop in the end to sort everything.
for (var i in seriesData) {
seriesData[i].data.sort(function(a, b) {
if (a.x > b.x) {
return 1;
}
if (b.x > a.x) {
return -1;
}
return 0;
});
}
The other problem is that the data array contains in correct data because of this line
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
so I changed it to this
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push({
task_id: interval.task_id,
x: (interval.to + task.intervals[j + 1].from) / 2,
y: null,
from: (interval.to + task.intervals[j + 1].from) / 2,
to: (interval.to + task.intervals[j + 1].from) / 2
});
}
here is the fixed plnkr
http://plnkr.co/edit/OEMuVfTMhHNQsTYGUyuy?p=preview
Please read this link to improve highcharts performance. A few months ago Highcharts released boost.js to improve chart performance with millions of data points.

Why is my addPoint() not recognized as a function in my highcharts code?

I am working with Highcharts and live data. I have my ajax all set up properly it seems and have a setTimeout called to bring in live data. Whenever that data comes in I want to addPoint() to my series and draw the new graph (shifting to the left). Below is my code, line 85 is the .addPoint call but you will see in the console that it is showing as not a function or undefined.
I know from the console as well that I am a calling my data correctly from my chart (chart1.data.series[0] returns and object). Here is the highcharts documentation on series data and addPoint : < http://api.highcharts.com/highcharts#Series.addPoint >
Any idea where I went wrong? I am new to js 1 year <. so I appreciate all your help!
<!doctype html>
<html>
<head>
<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>
</head>
<body>
<div id="container" style="width:100%"></div>
</body>
<script>
chart1 = {
yAxisMin: null,
yAxisMax: null
};
// empty objects for our data and to create chart
seriesData = [];
BPM = [];
time1 = [];
// console.log(chart1.data.series);
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
function requestData() {
var url = 'http://msbandhealth.azurewebsites.net/odata/PulsesAPI/';
$.ajax({
url: url,
dataType: 'json',
context: seriesData,
success: function(data) {
shift = chart1.data.series[0].data.length > 20;
// structure our data
for (var i = 0; i < data.value.length; i++) {
bpm = data.value[i].BPM;
time = data.value[i].Time;
console.log(time);
this.push([time, BPM]);
BPM.push(bpm);
time1.push(time);
}
// console.log(series[0]);
// find the highest pulse so we can set it to the highest y point
chart1.yAxisMax = (function(array) {
var pulse_array = [];
for (var i = 0; i < array.length; i++) {
if (array[i] != null) {
pulse_array.push(array[i]);
}
}
return Math.max.apply(Math, pulse_array);
})(BPM);
// find the lowest pulse rate and set it to lowest y point
chart1.yAxisMin = (function(array) {
var pulse_array = [];
for (var i = 0; i < array.length; i++) {
if (array[i] != null) {
pulse_array.push(array[i]);
}
}
return Math.min.apply(Math, pulse_array);
})(BPM);
// set our data series and create new chart
chart1.data.series[0].data = BPM;
chart = new Highcharts.Chart(chart1.data);
$('#container').css({
height: '400px'
});
chart1.data.series[0].addPoint(BPM, true, true);
// setTimeout(requestData, 3000);
console.log(chart1.data.series);
}
});
}
// give highcharts something to render to
container = document.getElementById("container");
chart1.data = {
chart: {
renderTo: container,
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: requestData()
}
},
title: {
text: ' Real Time Pulse Analysis'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
min: chart1.yAxisMin,
max: chart1.yAxisMax,
title: {
text: 'Heart Rate'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Beats Per Minute',
data: []
}]
};
});
});
</script>
</html>
You should use reference to chart and then call addPoint, instead of refer to chart configuration object.
Correct form: chart.series[0].addPoint()

Categories plugin for jQuery Flot library not working

I'm making a chart using jQuery Flot library in which x-axis contains text unit (month) instead of number. So I use categories plugin for Flot and clone example code from its main website. But the months does not show, just the bargraph displayed. The code is like following:
The code snippet gets problem is between commented block "site stats chart". I upload full code just for you all know what I am doing and can detect if there is issue in other parts that affect this code snippet.
Flot categories is downloaded from http://www.flotcharts.org/flot/jquery.flot.categories.js
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ProjectDashboard.aspx.cs" Inherits="SELPORTAL.project.ProjectDashboard" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Project Dashboard</title>
<script type="text/javascript">
pageSetUp();
loadScript("js/plugin/flot/jquery.flot.cust.js", loadFlotResize);
function loadFlotResize() {
loadScript("js/plugin/flot/jquery.flot.resize.js", loadFlotFillbetween);
}
function loadFlotFillbetween() {
loadScript("js/plugin/flot/jquery.flot.fillbetween.js", loadFlotOrderBar);
}
function loadFlotOrderBar() {
loadScript("js/plugin/flot/jquery.flot.orderBar.js", loadFlotPie);
}
function loadFlotPie() {
loadScript("js/plugin/flot/jquery.flot.pie.js", loadFlotCategories);
}
function loadFlotCategories() {
loadScript("js/plugin/flot/jquery.flot.categories.js", loadDebug);
}
function loadDebug() {
loadScript("js/plugin/flot/jquery.flot.debug.js", loadFlotToolTip);
}
function loadFlotToolTip() {
loadScript("js/plugin/flot/jquery.flot.tooltip.js", generateAllFlotCharts);
}
/* chart colors default */
var $chrt_border_color = "#efefef";
var $chrt_grid_color = "#DDD"
var $chrt_main = "#E24913"; /* red */
var $chrt_second = "#6595b4"; /* blue */
var $chrt_third = "#FF9F01"; /* orange */
var $chrt_fourth = "#7e9d3a"; /* green */
var $chrt_fifth = "#BD362F"; /* dark red */
var $chrt_mono = "#000";
var MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var categories = {};
var ongoingProjects = [];
var issues = {};
$(function () {
var jsonData = $("#projectsYearCategory").val();
parseDataReceived(jsonData);
fillOngoingTable();
});
function parseDataReceived(json) {
var obj = JSON.parse(json);
categories = obj.allProjects;
ongoingProjects = obj.ongoingProjects;
issues = obj.issues;
for (var i = 0; i < ongoingProjects.length; i++) {
ongoingProjects[i].deadline = getDateFromJsonDate(ongoingProjects[i].deadline);
}
for (var category in issues) {
for (var i = 0; i < issues[category].length; i++) {
issues[category][i] = [getTickDateString(getDateFromJsonDate(issues[category][i].Item1)), issues[category][i].Item2];
}
}
console.log(categories);
console.log(ongoingProjects);
console.log(issues);
}
function getDateFromJsonDate(d) {
return new Date(parseInt(d.substr(6)));
}
function getDateString(d) {
return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
}
function getTickDateString(d) {
return MONTH_NAMES[d.getMonth()] + "-" + d.getFullYear();
}
function fillOngoingTable() {
var tblBody = $('#tbl_ongoing tbody');
for (var i = 0; i < ongoingProjects.length; i++) {
var row = $('<tr>');
row.append($('<td>').text(ongoingProjects[i].name));
row.append($('<td>').text(ongoingProjects[i].model));
row.append($('<td>').text(ongoingProjects[i].grade));
row.append($('<td>').text(getDateString(ongoingProjects[i].deadline)));
tblBody.append(row);
}
}
function generateAllFlotCharts() {
for (var category in categories) {
var projects = categories[category];
var ongoing = [];
var upcoming = [];
var completed = [];
var drop = [];
for (var year in projects) {
ongoing.push([year, projects[year]["Ongoing"]]);
upcoming.push([year, projects[year]['Upcoming']]);
completed.push([year, projects[year]['Completed']]);
drop.push([year, projects[year]['Drop']]);
}
var ds = new Array();
ds.push({
data: ongoing,
label: "Ongoing",
bars: {
show: true,
barWidth: 0.1,
order: 1,
}
});
ds.push({
data: upcoming,
label: "Upcoming",
bars: {
show: true,
barWidth: 0.1,
order: 2,
}
});
ds.push({
data: completed,
label: "Completed",
bars: {
show: true,
barWidth: 0.1,
order: 3,
}
});
ds.push({
data: drop,
label: "Drop",
bars: {
show: true,
barWidth: 0.1,
order: 4,
}
});
//Display graph
$.plot($("#bar-chart-" + category.toLowerCase()), ds, {
colors: [$chrt_second, $chrt_fourth, "#666", "#BBB"],
grid: {
show: true,
hoverable: true,
clickable: true,
tickColor: $chrt_border_color,
borderWidth: 0,
borderColor: $chrt_border_color,
},
legend: true,
xaxis: {
tickDecimals: 0,
},
yaxis: {
tickDecimals: 0,
min: 0,
},
tooltip: true,
tooltipOpts: {
content: "<span>%s: %y project(s)</span>",
defaultTheme: false
}
});
}
/* pie chart */
if ($('#pie-chart').length) {
var data_pie = [];
var series = Math.floor(Math.random() * 10) + 1;
for (var i = 0; i < series; i++) {
data_pie[i] = {
label: "Series" + (i + 1),
data: Math.floor(Math.random() * 100) + 1
}
}
$.plot($("#pie-chart"), data_pie, {
series: {
pie: {
show: true,
innerRadius: 0.5,
radius: 1,
label: {
show: false,
radius: 2 / 3,
formatter: function (label, series) {
return '<div style="font-size:11px;text-align:center;padding:4px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
},
threshold: 0.1
}
}
},
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#000", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: [5, 10], // distance from grid edge to default legend container within plot
backgroundColor: "#efefef", // null means auto-detect
backgroundOpacity: 1 // set to 0 to avoid background
},
grid: {
hoverable: true,
clickable: true
},
});
}
/* end pie chart */
/* site stats chart */
if ($("#line-chart-issues").length) {
var issuesSDK = issues["SDK"];
var issuesMobile = issues["Mobile"];
var issuesCamera = issues["Camera"];
console.log(issuesSDK);
console.log(issuesMobile);
console.log(issuesCamera);
var data = [["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9]];
$.plot("#line-chart-issues", [data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
}
/* end site stats */
}
</script>
</head>
The categories plugin requires an array of categories in the xaxis options:
xaxis: {
mode: "categories",
categories: ["Category One", "Category Two", "Category Three"] // I don't see you doing this anywhere in your code!
}
You just need to update the main library from http://www.flotcharts.org/flot/jquery.flot.js to make all compatible
1:be sure to added this java script to your code
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.categories.js"></script>
and your function can like this
$(function() {
var data = [ ["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9] ];
$.plot("#placeholder", [ data ], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
});

Categories

Resources