highcharts with only javascript and no jquery - javascript

So without jquery I want to update highcharts with new data live. I have a chart that displays data from a database, and I am doing a http get request to get the data every few seconds. I am able to grab the data correctly, but when I push the new data onto the series variable for the chart, the graph doesn't update in real time. It only updates when I refresh. How can I fix this? I am using highcharts in angularjs.

you should call series.addPoint() instead of just updating the data array

please see here http://jsfiddle.net/9m3fg/1
js:
var myapp = angular.module('myapp', ["highcharts-ng"]);
myapp.controller('myctrl', function ($scope) {
$scope.addPoints = function () {
var seriesArray = $scope.chartConfig.series
var newValue = Math.floor((Math.random() * 10) + 1);
$scope.chartConfig.xAxis.currentMax++;
//if you've got one series push new value to that series
seriesArray[0].data.push(newValue);
};
$scope.chartConfig = {
options: {
chart: {
type: 'line',
zoomType: 'x'
}
},
series: [{
data: [10, 15, 12, 8, 7, 1, 1, 19, 15, 10]
}],
title: {
text: 'Hello'
},
xAxis: {
currentMin: 0,
currentMax: 10,
minRange: 1
},
loading: false
}
});

From your code it looks like you want to add new series rather then new data if yes please see here: http://jsfiddle.net/bYx4a/
var app = angular.module('app', ["highcharts-ng"]);
app.controller("myCtrl", ['$scope', '$http', function ($scope, $http) {
var count = 0;
$scope.chartOptions = {
chart: {
type: 'line'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}]
};
$scope.addSeries = function () {
var newData = {
name: 'John',
data: [1, 4, 3]
};
$scope.chartOptions.series.push({
name: newData.name,
data: newData.data
})
};
}]);

Here is my solution for using Highcharts addPoint function in the highcharts-ng directive:
$scope.chart_realtimeForceConfig = {
options: {
chart: {
type: 'line',
},
plotOptions: {
series: {
animation: false
},
},
},
series: [
{
name: 'Fx',
data: []
},
],
func: function(chart) {
$timeout(function() {
chart.reflow();
$scope.highchart = chart;
}, 300);
socket.on('ati_sensordata', function(data) {
if (data) {
var splited = data.split('|');
if (splited.length >= 6) {
var val = parseFloat(splited[5]);
var shift = chart.series[0].data.length > 100;
chart.series[0].addPoint(val, true, shift, false);
}
}
});
},
loading: false
}

Related

How to poll data using Ajax request?

I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);
...
...
function RefreshGraph() {
var options = {
chart: {
type: 'spline'
},
title: {
text: 'Text'
},
xAxis: {
title: {
text: 'TIMEFRAME'
},
categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
},
yAxis: {
title: {
text: 'NUMBER'
},
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 2
}
}
},
series: [{}]
};
Highcharts.ajax({
url: "/Home/GetData",
success: function (data) {
var formattedData = FormatData(data);
//Graph 1
options.series[0] = formattedData[0];
//Graph 2
options.series[1] = formattedData[1];
Highcharts.chart("container", options);
}
});
}
However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?
You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};
const chart = Highcharts.chart("container", options);
function RefreshGraph() {
Highcharts.ajax({
url: "/Home/GetData",
success: function(data) {
var formattedData = FormatData(data);
chart.update({
series: [formattedData[0], formattedData[1]]
});
}
});
}
setInterval(RefreshGraph, 3000);
Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update

Create Pie chart for each Json object

I have one Json with multiple array and foreach array I want to create Pie chart, but I don't know how to do it.
This is the array thet I have. And this is what I tried :
function Pie() {
$.getJSON("/Admin/Attivita/OreOggi", function (data) {
console.log(data);
var oreTecico = [];
var oreTecico = [];
var oreMalatia = [];
var oreStraordinario = [];
var oreInfortunio = [];
var oreFerie = [];
for (var i = 0; i < data.length; i++) {
nomeTecnico.push(data[i].nome);
oreTecico.push(data[i].odinario);
oreMalatia.push(data[i].malatia);
oreStraordinario.push(data[i].straordinario);
oreInfortunio.push(data[i].infortunio);
oreFerie.push(data[i].ferie);
};
// Build the chart
Highcharts.chart('zdravko', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Ore segnate oggi'
},
tooltip: {
pointFormat: '<b>{point.name}</b>: {point.y:.1f} h.'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: nomeTecnico[0],
colorByPoint: true,
data: [{
name: '',
y:0,
sliced: true,
selected: true
}, {
name: 'Odinario',
y: oreTecico[0]
}, {
name: 'Malatia',
y: oreMalatia[0]
}, {
name: 'Straordinario',
y: oreStraordinario[0]
}, {
name: 'Infortunio',
y: oreInfortunio[0]
}, {
name: 'Ferie',
y: oreFerie[0]
}]
}]
});
});
}
It shows only the last "data". I want to make fo each array one pie. If i have 100 arrays I want 100 pies.
UPDATE:
I added this :
data.forEach(function (el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('zdravko').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
The chartData is array of undefined objects.
Is it possible to make for or foreach inside Highcharts?
You need to use the Highcharts.chart method in a loop, for example:
var data = [{
data1: 12,
data2: 25
}, {
data1: 67,
data2: 11
}];
data.forEach(function(el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('container').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
Live demo: http://jsfiddle.net/BlackLabel/x95pbw7j/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.chart

Hide a category when a series name has no value attributed to it highchart

I have simplified my graph below for demo purposes but i have a lot of categories but not all series names will have a value of those categories. So when i select that series name how would i go about making 0 value categories disappear.
For example below when selecting person 1 the service 1 category should disappear instead of remain with no bars for it
Highcharts.chart('container', {
chart : {type: 'column'},
xAxis: {
categories: ["service1", "service2", "service3", "service"] ,
showEmpty : true ,
ordinal: false
},
series: [{
name: 'person1',
data: [0,2,3],
},
{ name : 'person2',
data: [10,6,5]
}]
});
link to the code https://jsfiddle.net/uroepk1j/
ppotaczek's Code from JSFiddle
Highcharts.chart('container', {
chart: {
type: 'column',
ignoreHiddenSeries: true
},
plotOptions: {
column: {
pointPlacement: null,
events: {
legendItemClick: function() {
var points = this.data,
hideCategory = false,
breaks = [],
stop,
series = this.chart.series;
this.chart.xAxis[0].update({
breaks: []
});
this.visible = !this.visible;
points.forEach(function(p, i) {
stop = false;
series.forEach(function(s) {
if (!stop && (!s.visible || s.data[i].y === 0)) {
hideCategory = true;
} else {
stop = true;
hideCategory = false;
}
}, this);
if (hideCategory) {
breaks.push({
from: i - 0.5,
to: i + 0.5,
breakSize: 0
})
}
hideCategory = false;
}, this);
this.visible = !this.visible;
this.chart.xAxis[0].update({
breaks: breaks
});
}
}
},
},
xAxis: {
categories: ['Col 1', 'Col 2', 'Col 3']
},
series: [{
name: 'person1',
data: [2, 0, 3],
},
{
name: 'person2',
data: [10, 1, 5]
}
]
});
Thanks for your help
You can use broken-axis module and insert breaks in place of the category in which there are no points, for example:
plotOptions: {
column: {
grouping: false,
pointPlacement: null,
events: {
legendItemClick: function() {
if (!this.visible) {
breaks[this.index] = {}
this.chart.xAxis[0].update({
breaks: breaks
});
} else {
breaks[this.index] = {
from: this.xData[0] - 0.5,
to: this.xData[0] + 0.5,
breakSize: 0
}
this.chart.xAxis[0].update({
breaks: breaks
});
}
}
}
},
}
Live demo: http://jsfiddle.net/BlackLabel/4utq7e3n/
API Reference: https://api.highcharts.com/highcharts/xAxis.breaks

Highcharts bar chart wont animate

Not sure why because I have done it in the past, but I have a Highcharts bar chart and it won't animate. This is the declaration of the chart,
function initializeData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push({
name: setName($scope.jsondata[x].name),
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 5000);
}
function updateData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
console.debug("here");
for (x = 0; x < 5; x++) {
$scope.chart.series[0].data[x].update({
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'category',
labels: {
style: {
fontSize: '11px'
}
}
},
yAxis: {
min: 0,
max: 100,
title: {
text: 'Total Score',
align: 'high'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Total Score <b>{point.y:.3f}</b>'
},
series: [{
name: 'Active Users',
data: [],
dataLabels: {
enabled: true,
rotation: 30,
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif'
},
format: '{point.y:.3f}', // one decimal
}
}]
});
And as you can see I have animate : true, so I am not sure what is the problem here. I have this older plunker where all of the data is in separate series, but it animates fine. But this is the plunker I am working on and having trouble with. They are like identical basically. In the newer one I broke out the initialization of data into its own method, but that is the only real main difference.
Some edits:
So as I was saying, I have done things this way with an areaspline chart (I know it was said they work a bit different but they are set up identically).
function initializeData() {
$interval.cancel(mainInterval);
$scope.previousPackets = '';
$http.get("https://api.myjson.com/bins/nodx").success(function(returnedData) {
var newdata = [];
var x = (new Date()).getTime();
for (var step = 9; step >= 0; step--) {
newdata.push([x - 1000 * step, 0]);
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 2000);
}
function updateData() {
$http.get(url + acronym + '/latest').success(function(returnedData) {
var x = (new Date()).getTime();
if ($scope.previousPackets != returnedData[0].numPackets) {
$scope.chart.series[0].addPoint([x, returnedData[0].numPackets], true, true);
$scope.previousPackets = returnedData[0].numPackets;
} else {
$scope.chart.series[0].addPoint([x, 0], true, true);
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Packets'
},
plotLines: [{
value: 0,
width: 1,
color: '#d9534f'
}]
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.y) + ' packets<b> | </b>' + Highcharts.dateFormat('%H:%M:%S', this.x);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Packets',
data: []
}]
});
I also updated the first chunk of code with the initializeData() method and updateData() method which are seemingly identical in both different charts.
It looks like it plays an important role if you provide your data at chart initialization or after. For simplicity I refactored your code a little
function initializeChart(initialData, onload) {
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: onload
}
....
series: [{
name: 'Active Users',
data: initialData,
dataLabels: {
enabled: true,
format: '{point.y:.3f}', // one decimal
}
}]
});
}
function getData(callback) {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push([setName(ret[x].name), ret[x].data]);
}
callback(newdata);
});
}
As a result your two planks are in essense reduced to two methods below. The first initializes chart with preloaded data and the second updates data in existing chart.
function readDataFirst() {
getData(function(newdata) {
initializeChart(newdata);
});
}
function initializeChartFirst() {
initializeChart([], function() {
getData(function(newdata) {
$scope.chart.series[0].setData(newdata);
})
});
}
The first one animates fine while the second does not. It looks like highcharts skips animation if dataset is not initial and is treated incompatible.
However if you really want to have animation in your current plant (chart first workflow) you can achieve that by initializing first serie with zeros and then with the real data. This case it will be treated as update
function forceAnimationByDoubleInitialization() {
getData(function(newdata) {
initializeChart([]);
var zerodata = newdata.map(function(item) {
return [item[0], 0]
});
$scope.chart.series[0].setData(zerodata);
$scope.chart.series[0].setData(newdata);
});
All these options are available at http://plnkr.co/edit/pZhBJoV7PmjDNRNOj2Uc

Highcharts reloading issue with Backbone.js

I'm struggling to solve a problem I have with getting a chart to be redrawn after navigating to another view and then return back to the same chart view.
I'm using Backbone.js and Underscore as a MVC and templating solution for my application.
When I navigate to the charting page initially it works great, but if I move away and then come back I get a `TypeError: chart.series[0] is undefined in the console log.
I have highlighted line where the error occurs in the code below, close to the end.
My thought is that I may need to destroy() the chart at some point, but I'm unsure where I would do this and if it would solve my problem.
I recently changed the script to now use HighStock 'Highstock JS v1.3.6 (2013-10-04)' from earlier HighCharts ver 2.3.5, where it appeared that I did not have this issue.
The app is live online if anyone really needs or wants to see it in action, let me know.
The following code section is the function thatis called by the Backbone router.
If there is a need for other sections of code, please let me know.
I'll be grateful for any advice.
EDIT:
I have managed to get this in JSFiddle for anyone to view the problem.
Clickty clack your fury tailless one here http://jsfiddle.net/rockwallaby/pqKWj
When you first run it up, you will get a trend being displayed.
Then hit the 'Go to a different page' link, you will get a fairly blank page.
On that page there is a link to bring you back to the trend page.
Hitting that link brings you back but the trend does not get rendered correctly due to the above mentioned error.
//=================================================================================
// trendsBattery
// A simple trend view showing Battery Volts and Solar Charge
//
window.trendsBattery = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendsTemplate),
chart: null,
chartoptions:{
chart: {
renderTo: 'chart-container',
},
rangeSelector: {
enabled: false,
},
title:{
text:'Battery Volts & Solar Amps'
},
xAxis: {
type:'datetime',
dateTimeLabelFormats: {month:'%e. %b',year:'%b'}
},
yAxis: [{
title :{text: 'Battery Volts'},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0',
},
{
title :{text: 'Solar Charge Amps'},
min: 0,
max: 16,
opposite: true,
},
],
series:[
{yAxis: 0, data: [], type: 'line', step: true, name: 'Battery Vdc'},
{yAxis: 1, data: [], type: 'line', step: true, name: 'Solar Amps'},
],
},
render:function() {
that = this;
$(this.el).html(this.template());
this.chartoptions.chart.width = (windowWidth);
this.chartoptions.chart.height = (windowHeight - 150);
setTimeout(function() {
chart = new Highcharts.StockChart(that.chartoptions);
chart.events ={load: that.requestData(this.chart) };
},20);
return this;
},
requestData: function(chart){
var querystring = '//myHostServer.com/myFolder/myPHP.php';
jQuery.get(querystring, null, function(csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
};
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0]) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
};
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
},
});
I just updated jsfiddle with the suggestion I provided in comment, it's working.
window.trendView = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendTemplate),
chart: null,
getChartOptions: function () {
return {
chart: {
animation: true,
renderTo: 'chart-container',
backgroundColor: '#fff'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Battery Volts & Solar Amps'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
} // don't display the dummy year:
},
yAxis: [{
title: {
text: 'Battery Volts'
},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0'
}, {
title: {
text: 'Solar Charge Amps'
},
min: 0,
max: 16,
opposite: true
}],
series: [{
yAxis: 0,
data: [],
type: 'line',
step: true,
name: 'Battery Vdc'
}, {
yAxis: 1,
data: [],
type: 'line',
step: true,
name: 'Solar Amps'
}]
}
},
render: function () {
that = this;
$(this.el).html(this.template());
var chartOptions = that.getChartOptions();
chartOptions.chart.width = (windowWidth - 50);
chartOptions.chart.height = (windowHeight - 50);
setTimeout(function () {
chart = new Highcharts.StockChart(chartOptions);
chart.events = {
load: that.requestData(this.chart)
};
}, 20);
return this;
},
requestData: function (chart) {
var querystring = '//paulalting.com/hydrosolar/clientGET.php?id=trendVolts&start=6400&size=200';
console.log(querystring);
jQuery.get(querystring, null, function (csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0], 10) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
}
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
}
});
here is the link
http://jsfiddle.net/pqKWj/14/
If you are interested let me know I see some more similar problems in the code, which I think fine for now, but will create issues, when you have 2 charts in the same page etc. we can talk

Categories

Resources