Real Time Bar chart using Highcharts and AngularJs - javascript

Using a Highcharts example (here), I have loaded a bar chart in AngularJs.
HTML code below:
<!DOCTYPE html>
<html ng-lang="en" ng-app="myModule">
<head>
<meta charset="ISO-8859-1">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.7/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<title>Insert title here</title>
</head>
<script>
angular.module('myModule',[])
.controller('myController',function($q, $scope, $http){
$scope.cnt = 1;
var t = 0;
setInterval(function(cnt){
fetchData($scope.cnt).then(function(success){
$scope.chartOptions={
chart: {
type: 'bar',
events:{
load:function(){
var rowClass = this.series[0];
console.log("rowClass : "+rowClass);
}
}
},
title: {
text: 'ClassNames By Count Chart'
},
subtitle: {
text: 'Admin Chart'
},
xAxis: {
categories: $scope.rows,
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 80,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Year 1800',
data: (function(){
var data = [];
var i;
console.log("In Series function() : $scope.num : "+$scope.num ); //Update is being done propertly
for(i=1;i<4;i=i+1){
data.push($scope.num[i]);
}
return data;
}())
}, {
name: 'Year 1900',
data: [133, 156, 947, 408, 6]
}, {
name: 'Year 2000',
data: [814, 841, 3714, 727, 31]
}, {
name: 'Year 2016',
data: [1216, 1001, 4436, 738, 40]
}]
};
if(t==0){
t = t+1;
Highcharts.chart('container',$scope.chartOptions);
}
},function(error){
console.log("in error functio : "+error);
});
},2000);
var cnt = 0;
var str = "str";
setInterval(function(){
str = str+cnt;
cnt++;
$http({
method: "GET",
url : "http://localhost:8080/hello/"+str+"/3"
}).then(function success(data){
}, function error(data){
console.log("error "+data.data);
});
},5000);
var fetchData = function(cnt){
$scope.cnt = $scope.cnt+1;
var deferred = $q.defer();
$http({
method : "GET",
url : "http://localhost:8080/hello"
}).then(function mySuccess(response) {
$scope.myRes = response.data;
$scope.rows = $scope.myRes;
var i;
$scope.num = [];
for(i=0;i<4;i=i+1){
$scope.num.push(++cnt*110);
}
deferred.resolve();
}, function myError(response) {
console.log("error");
$scope.myRes = response;
deferred.reject();
});
return deferred.promise;
};
});
</script>
<body ng-controller="myController">
<hcbar options="chartOptions"></hcbar>
<div id="container"></div>
</body>
</html>
Now I require to load the bar counts in the chart to be loaded dynamically that is as the count is updated in Database the new values have to be reflected in the chart (Real Time Data)
You will see I ahve written the data : function in my file which updates the data array in a loop:
series: [{
name: 'Year 1800',
data: (function(){
var data = [];
var i;
console.log("In Series function() : $scope.num : "+$scope.num ); //Update is being done propertly
for(i=1;i<4;i=i+1){
da.push($scope.num[i]);
}
returndata;
}())
},
The updated values are correctly printed in console but are NOT BEING REFLECTED IN THE CHART BAR!
I know there is this function addPoint() which adds a point to the array. But here I do not want a new Object in the series array but the updated values in the series[0].data array!
How can this be accomplished?

If you put your values in $scope and use like following.
series: [{
data: [
{ name: 'Year 1800', y: $scope.num1, color: 'red' },
{ name: 'Year 1900', y: $scope.num2, color: 'green' },
{ name: 'Year 2000', y: $scope.num3, color: 'blue' },
{ name: 'Year 2016', y: $scope.num4, color: 'yellow' }
]
}],
when you will update $scope.num1, it will definitely update in chart.
here is a WORKING Example.
$scope.chartOptions = {
chart: {
type: 'column',
spacingLeft: 0,
spacingRight: 0,
height: 300
},
title: {
text: ''
},
xAxis: {
categories: ['1800', '1900', '2000', 2016'],
crosshair: true
},
yAxis: {
min: 0,
tickInterval: 20,
title: {
text: ''
},
labels:
{
enabled: false
}
},
legend: {
enabled: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
credits: {
enabled: false
},
series: [{
data: [
{ name: 'Year 1800', y: $scope.num1, color: 'red' },
{ name: 'Year 1900', y: $scope.num2, color: 'green' },
{ name: 'Year 2000', y: $scope.num3, color: 'blue' },
{ name: 'Year 2016', y: $scope.num4, color: 'yellow' }
]
}]
};

Related

How to show multiple graphs in drilldown (highcharts)?

NET MVC Project, where I use Highcharts. In my charts i have columns and a spline.
I have already implemented drilldown for my chart and it works perfectly, but only for the columns. On the first level the columns and the spline is shown, but when I trigger drilldown only the columns are shown. data2 should be the spline.
var mychart = Highcharts.chart('container', {
chart: {
zoomType: 'xy',
spacingBottom: 40,
spacingTop: 40,
events: {
// DRILLDOWN
drilldown: function (e) {
//Some variables id, func
$.getJSON(`/Home/GetDataForMinuteDrilldown?id=${id}&function=${func}`, function (data) {
console.log(data);
var durationArrMinutes = data.map(function (item) {
return item['minuteavg'];
});
var errorArrayMinutes = data.map(function (item) {
return item['errorsperminute']
});
var minuteArray = data.map(function (item) {
return {
name: drill + ":" + item['minute'],
y: item['minuteavg'],
drilldown: item['minute']
};
});
data2 = {
name: 'Errors per Minute',
type: 'spline',
data: errorArrayMinutes,
tooltip: {
valueSuffix: ' '
}
}
data = {
name: 'Average Duration per Minute',
type: 'column',
yAxis: 1,
data: minuteArray,
tooltip: {
valueSuffix: ' ms'
},
data2 //I think this is the error, but I i know no solution
}
console.log('Data:')
console.log(data);
mychart.hideLoading();
mychart.addSeriesAsDrilldown(e.point, data);
});
}
}
},
title: {
text: 'Performance and Error Analytics'
},
subtitle: {
text: 'Analytics of: ' + func
},
xAxis: [{
type: 'category',
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Errors',
style: {
color: Highcharts.getOptions().colors[2]
}
}
}, { // Secondary yAxis
title: {
text: 'Duration in ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'center',
x: 0,
verticalAlign: 'bottom',
y: 50,
floating: true,
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || // theme
'rgba(255,255,255,0.25)'
},
series: [{
name: 'Average Duration per Hour',
type: 'column',
yAxis: 1,
data: durationPerHourArray,
tooltip: {
valueSuffix: ' ms'
}
}, {
name: 'Errors',
type: 'spline',
data: errorArray,
tooltip: {
valueSuffix: ' '
}
}],
drilldown: {
activeAxisLabelStyle: {
textDecoration: 'none',
fontStyle: 'normal',
color: 'black'
},
series: []
}
});
The addSeriesAsDrilldown method allows to add only one series to drilldown. From source code:
Chart.prototype.addSeriesAsDrilldown = function (point, options) {
this.addSingleSeriesAsDrilldown(point, options);
this.applyDrilldown();
};
Instad of addSeriesAsDrilldown, you can use internal addSingleSeriesAsDrilldown method to add both series and call applyDrilldown:
mychart.addSingleSeriesAsDrilldown(e.point, data);
mychart.addSingleSeriesAsDrilldown(e.point, data2);
mychart.applyDrilldown();
Live demo: http://jsfiddle.net/BlackLabel/obukspae/
Source code: https://code.highcharts.com/modules/drilldown.src.js

highchart csv export custom filename and value

Please refer below JS fiddle link.
https://jsfiddle.net/2pd1natw/1/
// this is my JS for reference
$(function () {
var k = 0;
$('#container').highcharts({
chart: {
type: 'column',
zoomType: 'xy',
events: {
drilldown: function (e){
if (!e.seriesOptions) {
var chart = this,
drilldowns = {
'2015':{
name: '2015',
data: [
['Q4-2015',89]
]
},
'2016':{
name: '2016',
data: [
['Q2-2016',95],
['Q3-2016',99]
]
}
},
drilldownsLines = {
'2015':{
type: 'spline',
name: '2015',
data: [
['Q4-2015',11.45]
],
yAxis: 1
},
'2016':{
type: 'spline',
name: '2016',
yAxis: 1,
data: [
['Q2-2016',11.2],
['Q3-2016',11.5]
]
}
},
series = drilldowns[e.point.name],
seriesLine = drilldownsLines[e.point.name];
chart.addSingleSeriesAsDrilldown(e.point, series);
chart.addSingleSeriesAsDrilldown(e.point, seriesLine);
chart.applyDrilldown();
}
}
}
},
title: {
text: 'Rental & Capital Value Trend'
},
exporting: {
enabled: true,
csv:{
columnHeaderFormatter:function(item, key, series){
if(key === '' || key === undefined){
return 'Period';
}else if(key === 'y' && k == 0){
k = k + 1;
return 'Rental Value (INR/SF/Month)';
}else if(key === 'y' && k == 1){
k = 0;
return 'Capital Value (INR/SF)';
}
}
},
buttons:{
contextButton:{
menuItems: [{
textKey: 'downloadCSV',
onclick: function (){
this.downloadCSV();
}
}]
}
}
},
xAxis: {
type: 'category',
},
yAxis: [{
min: 0,
title: {
text: 'Rental Value (INR/SF/Month)'
},
labels: {
format: '{value}'
}
}, {
min:0,
tickInterval:5,
title: {
text: 'Capital Value (INR/SF)'
},
labels: {
format: '{value} K'
},
opposite:true
}],
tooltip:{
formatter:function(){
var s='';
$.each(this.points, function () {
if(this.series.type == 'spline'){
s += '<br/>Capital Value : ' + this.y+ 'K';
}else{
s += '<br/> Rental Value : ' + this.y;
}
});
return s;
},
shared:true
},
legend: {
layout: 'horizontal',
align: 'left',
size: '12px',
x: 50,
verticalAlign: 'bottom',
y: 20,
floating: true
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: false
}
}
},
series: [{
name: 'Renatl Value (INR/SFT/Month)',
color: '#EE8908',
data: [
{
name: '2015',
y: 89,
drilldown: true
}, {
name: '2016',
y: 90,
drilldown: true
}
]
},{
name:'Capital Value (INR/SF)',
color:'#F8BB6C',
type:'spline',
yAxis:1,
data:[
{
name:'2015',
y:11.45
},{
name:'2016',
y:15.22
}
],
tooltip: {
valueSuffix: 'K'
}
}
],
drilldown: {
/*activeAxisLabelStyle: {
textDecoration: 'none'
},*/
series: []
}
});
});
There are two scenarios where I got stuck.
when I try to export chart as csv after drill down downloaded file name should be "Quarterly rental-capital trend" and before drill down "Yearly rental-capital trend".
e.g. before drill down file name should be like "Yearly rental-capital trend.csv"
after drill down file name should be like "Quarterly rental-capital trend.csv"
after exporting to csv the capital value should be append with "K".
e.g. period | rental value | capital value
2015 | 90 | 11.15 K
Any help will be appreciated and thanks and advance.

spline is not plotting after drilldown - HighCharts

I am working with highCharts drilldown. My graph is plotting proper before drilldown. The column and spline is properly getting plot according to X-axis and Y-axis in graph but after drilldown the graph spline is not draw according to Y-axis. I want to plot spline as like before drilldown.
Here is my html
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/drilldown.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Here is my js code.
$(function () {
$('#container').highcharts({
chart: {
type: 'column',
zoomType: 'xy',
events: {
drilldown: function (e){
if (!e.seriesOptions) {
var chart = this,
drilldowns = {
'2015':{
name: '2015',
data: [
['Q4-2015',89]
]
},
'2016':{
name: '2016',
data: [
['Q2-2016',95],
['Q3-2016',99]
]
}
},
drilldownsLines = {
'2015':{
type: 'spline',
name: '2015',
data: [
['Q4-2015',11.45]
]
},
'2016':{
type: 'spline',
name: '2016',
data: [
['Q2-2016',11.2],
['Q3-2016',11.5]
]
}
},
series = drilldowns[e.point.name],
seriesLine = drilldownsLines[e.point.name];
chart.addSingleSeriesAsDrilldown(e.point, series);
chart.addSingleSeriesAsDrilldown(e.point, seriesLine);
chart.applyDrilldown();
}
}
}
},
title: {
text: 'Rental & Capital Value Trend'
},
xAxis: {
type: 'category',
},
yAxis: [{
min: 0,
title: {
text: 'Rental Value (INR/SF/Month)'
},
labels: {
format: '{value}'
}
}, {
min:0,
tickInterval:5,
title: {
text: 'Capital Value (INR/SF)'
},
labels: {
format: '{value} K'
},
opposite:true
}],
tooltip:{
formatter:function(){
var s='';
$.each(this.points, function () {
if(this.series.type == 'spline'){
s += '<br/>Capital Value : ' + this.y+ 'K';
}else{
s += '<br/> Rental Value : ' + this.y;
}
});
return s;
},
shared:true
},
legend: {
layout: 'horizontal',
align: 'left',
size: '12px',
x: 50,
verticalAlign: 'bottom',
y: 20,
floating: true
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: false
}
}
},
series: [{
name: 'Renatl Value (INR/SFT/Month)',
color: '#EE8908',
data: [
{
name: '2015',
y: 89,
drilldown: true
}, {
name: '2016',
y: 90,
drilldown: true
}
]
},{
name:'Capital Value (INR/SF)',
color:'#F8BB6C',
type:'spline',
yAxis:1,
data:[
{
name:'2015',
y:11.45
},{
name:'2016',
y:15.22
}
],
tooltip: {
valueSuffix: 'K'
}
}
],
drilldown: {
/*activeAxisLabelStyle: {
textDecoration: 'none'
},*/
series: []
}
});
});
On drilldown events you are creating new spline series and you don't specify y axis for them - by default they will be scaled with the use of the first y axis.
Specify a correct yAxis (should be 1 in your example) for the series and the spline will be drawn as you expect.
drilldownsLines = {
'2015':{
type: 'spline',
name: '2015',
data: [
['Q4-2015',11.45]
],
yAxis: 1
},
'2016':{
type: 'spline',
name: '2016',
yAxis: 1,
data: [
['Q2-2016',11.2],
['Q3-2016',11.5]
]
}
},
example: https://jsfiddle.net/2pd1natw/

Pass Ajax data in highcharts Combination chart

I'm trying to pass the data(line data and pie_data) in a combination chart. I'm able to pass the pie_data but unable to pass the line data. Here is my jsFiddle Link
Please suggest where I'm going wrong?
Here is my code.
$(function () {
var line_data = [{ // this is AJAX returned line_data.
'data': [
[1383741000000, 1608.3000000000002],
[1383741900000, 1611.9999999999973],
[1383742800000, 1612.299999999997]
],
'name': 'Bangalore'
}, {
'data': [
[1383741000000, 54.2],
[1383741900000, 54.300000000000004],
[1383742800000, 54.300000000000004]
],
'name': 'New Delhi'
}];
// this is AJAX returned pie_data.
// I'm able to get the pie chart, but not the line chart.
var pie_data = [['Jane',13], ['Jnanae',33] , ['Jasvdwdne',113]];
$('#container').highcharts({
chart: {
},
title: {
text: 'Combination chart'
},
xAxis: {
type: 'datetime'
},
series: [{
type: 'spline',
name: 'Average',
data: line_data,
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}, {
type: 'pie',
name: 'Total consumption',
data: pie_data,
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
}]
});
});
Try this out:- http://jsfiddle.net/5yzb2/6/
JS:-
$(function () {
var seriesOptions = [];
var line_data = [{ // this is AJAX returned line_data.
data: [
[1383741000000, 1608.3000000000002],
[1383741900000, 1611.9999999999973],
[1383742800000, 1612.299999999997]
],
name: 'Bangalore'
}, {
data: [
[1383741000000, 54.2],
[1383741900000, 54.300000000000004],
[1383742800000, 54.300000000000004]
],
name: 'New Delhi'
}];
// this is AJAX returned pie_data.
// I'm able to get the pie chart, but not the line chart.
var pie_data = [
['Jane', 13],
['Jnanae', 33],
['Jasvdwdne', 113]
];
//Adding all data seriesOptions
$.each(line_data, function (i, name) {
seriesOptions[i] = {
type: 'spline',
name: this.name,
data: this.data
};
});
seriesOptions[seriesOptions.length] = {
type: 'pie',
name: 'Total consumption',
data: pie_data,
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
};
$('#container').highcharts({
chart: {},
title: {
text: 'Combination chart'
},
xAxis: {
type: 'datetime'
},
tooltip: {
formatter: function () {
var s;
if (this.point.name) { // the pie chart
s = '' + this.point.name + ': ' + this.y + ' fruits';
} else {
s = '' + this.x + ': ' + this.y;
}
return s;
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '40px',
top: '8px',
color: 'black'
}
}]
},
series: seriesOptions
});
});

set different colors for each column in highcharts

I need to set different colors for each column in Highcharts graph dynamically. My Highcharts graph is:
options = {
chart: {
renderTo: 'chart',
type: 'column',
width: 450
},
title: {
text: 'A glance overview at your contest’s status'
},
xAxis: {
categories: ['Approved Photos', 'Pending Approval Photos',
'Votes', 'Entrants'],
labels: {
//rotation: -45,
style: {
font: 'normal 9px Verdana, sans-serif, arial'
}
}
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: 'Amount'
}
},
legend: {
enabled: false
},
series: []
};
series = {
name: "Amount",
data: [],
dataLabels: {
enabled: true,
color: '#000000',
align: 'right',
x: -10,
y: 20,
formatter: function () {
return this.y;
},
style: {
font: 'normal 13px Verdana, sans-serif'
}
}
};
The data is set this way:
for (var i in Data) {
if (parseInt(Data[i]) != 0) {
series.data.push(parseInt(Data[i]));
} else {
series.data.push(null);
}
}
options.series.push(series);
chart = new Highcharts.Chart(options);
How can I dynamically set different colors for each data point in this loop?
Here is another solution with the latest version of Highcharts (currently 3.0).
Set the colorByPoint option to true and define the color sequence that you want.
options = {
chart: {...},
plotOptions: {
column: {
colorByPoint: true
}
},
colors: [
'#ff0000',
'#00ff00',
'#0000ff'
]
}
Here is an example based upon Highcharts Column with rotated labels demo
When you add the value to the series.data you can also set the color using the point options e.g
series.data.push({ y: parseInt(Data[i]), color: '#FF0000' });
For more details about the point options see https://api.highcharts.com/class-reference/Highcharts.Point#color
Try either of these approaches:
Approach 1:
Highcharts.setOptions({ colors: ['#3B97B2', '#67BC42', '#FF56DE', '#E6D605', '#BC36FE'] });
Approach 2:
var colors = ['#3B97B2', '#67BC42', '#FF56DE', '#E6D605', '#BC36FE', '#000'];
$('#bar_chart').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: ''
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: false
}
}
},
series: [{
name: '',
colorByPoint: true,
data: [{
name: 'Blue',
y: 5.78,
color: colors[0]
}, {
name: 'Green',
y: 5.19,
color: colors[1]
}, {
name: 'Pink',
y: 32.11,
color: colors[2]
}, {
name: 'Yellow',
y: 10.04,
color: colors[3]
}, {
name: 'Purple',
y: 19.33,
color: colors[4]
}]
}]
});
i had colors from API response and 2 series. second series with dynamic colors.
following is sample to set dynamic colors while series mapping.
const response = [{
'id': 1,
'name': 'Mango',
'color': '#83d8b6',
'stock': 12.0,
'demand': 28,
},
{
id ': 2,
'name': 'Banana',
'color': '#d7e900',
'stock': 12.0,
'demand': 28,
}
];
let chartData: {
categories: [],
series: []
};
chartData.categories = response.map(x => x.name);
chartData.series.push({
name: 'Series 1',
type: 'column',
data: response.map(x => x.demand)
});
chartData.series.push({
name: 'Series 2',
type: 'column',
data: response.map(x => ({
y: x.stock,
color: x.color // set color here dynamically
}))
});
console.log('chartData: ', chartData);
you could also read more about Highcharts series Point and Marker

Categories

Resources