Total of values in HighCharts Pie Chart - javascript

Is there a way to get a grand total of values in legend or any other place in pie charts?
Here is the code with legend ,but instead of adding the total of percentage,i want to display the total of values..
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
width: 500,
borderWidth: 2
},
title: {
text: 'demo'
},
credits: {
enabled: false
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 30,
labelFormat: '{name} ({percentage:.1f}%)',
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '12px'
}
}
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.percentage, 2) + '%<br />' + '<b>' + this.point.name + '</b><br />Rs.: ' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
data: (function () {
var names = 'Ari,Bjartur,Bogi,Bragi,Dánjal,Dávur,Eli,Emil,Fróði,Hákun,Hanus,Hjalti,Ísakur,' +
'Johan,Jóhan,Julian,Kristian,Leon,Levi,Magnus,Martin,Mattias,Mikkjal,Nóa,Óli,Pauli,Petur,Rói,Sveinur,Teitur',
arr = [];
Highcharts.each(names.split(','), function (name) {
arr.push({
name: name,
y: Math.round(Math.random() * 100)
});
});
return arr;
}()),
showInLegend: true
}]
});
});

I would use the Renderer.text to annotate the chart (and not do it in the legend since you have so many data points).
chart: {
events: {
load: function(event) {
var total = 0; // get total of data
for (var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},
Fiddle example.

In addition to Mark's answer, to calculate the total, we do not need the for-loop statement. So, the code can be reduced.
chart: {
events: {
load: function(event) {
var total = this.series[0].data[0].total;
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},

Related

Adding Labels to the Left or Right of Highcharts Funnel Visualization

My current visualization is as follows:
$(function() {
var dataEx = [
['1 Visit', 352000],
['2 Visits', 88000],
['3+ Visits', 42000]
],
len = dataEx.length,
sum = 0,
minHeight = 0.05,
data = [];
//specify your percent of prior visit value manually here:
var perc = [100, 25, 48];
for (var i = 0; i < len; i++) {
sum += dataEx[i][1];
}
for (var i = 0; i < len; i++) {
var t = dataEx[i],
r = t[1] / sum;
data[i] = {
name: t[0],
y: (r > minHeight ? t[1] : sum * minHeight),
percent: perc[i], // <----- this here is manual input
//percent: Math.round(r * 100), <--- this here is mathematical
label: t[1]
}
}
console.log(dataEx, data)
$('#container').highcharts({
chart: {
type: 'funnel',
marginRight: 100,
events: {
load: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
var bBox = p.dataLabel.getBBox()
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
},
redraw: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
}
},
},
title: {
text: 'Guest Return Funnel',
x: -50
},
tooltip: {
//enabled: false
formatter: function() {
return '<b>' + this.key +
'</b><br/>Percent of Prior Visit: '+ this.point.percent + '%<br/>Guests: ' + Highcharts.numberFormat(this.point.label, 0);
}
},
plotOptions: {
series: {
allowPointSelect: true,
borderWidth: 12,
animation: {
duration: 400
},
dataLabels: {
enabled: true,
connectorWidth: 0,
distance: 0,
formatter: function() {
var point = this.point;
console.log(point);
return '<b>' + point.name + '</b> (' + Highcharts.numberFormat(point.label, 0) + ')<br/>' + point.percent + '%';
},
minSize: '10%',
color: 'black',
softConnector: true
},
neckWidth: '30%',
neckHeight: '0%',
width: '50%',
height: '110%'
//old options are as follows:
//neckWidth: '50%',
//neckHeight: '50%',
//-- Other available options
//height: '200'
// width: pixels or percent
}
},
legend: {
enabled: false
},
series: [{
name: 'Unique users',
data: data
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 500px; height: 400px; margin: 0 auto"></div>
I would like to do the following (a photo that clarifies what I would like is HERE):
Put the category names "1 Visit", "2 Visits", "3 Visits" to the LEFT of
the funnel.
Arrange the number of guest amount and percent for each category of the
funnel so that it appears like (INSIDE the funnel):
352K 100%
Right now I have the values as the full number like 352000 but I'm
wondering if there's a way to make all numbers with 000 at the end into
a "K" at the end.
It would be great if I could also add labels for those two values AT THE
TOP of the funnel ("Guests" and "Percent of Prior Visit").
Add 2 more labels to the RIGHT of the funnel called "Q1/17 TTM" and "Avg
Value" and have values be placed for each category of the funnel
below the labels. The values for "Q1/17 TTM" should be red and the
values for "Avg Value" should be gray.
The values for "Q1/17 TTM" begin at the "2 Visits" and end at the very
bottom (under the last category)
Values for "Avg Value" begin at the first category and end at the last
category.
At the very bottom of the visualization, have a value. Don't worry about
what this is (and this is the value $12.9M in the photo).
And I want these changes to still make the data processing algorithm to visualize small values work. I would really appreciate the help! Thank you.
There isn not any option in Highcharts to handle more than one datalabels, but you can use text SVGRenderer to add additional text elements, for example:
events: {
render: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
var bBox = p.dataLabel.getBBox();
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
});
if (p.dataLabel1) {
p.dataLabel1.destroy();
p.dataLabel2.destroy();
}
p.dataLabel1 = chart.renderer.text(p.name, p.dataLabel.x - 150, p.dataLabel.y + chart.plotTop - bBox.y).add();
p.dataLabel2 = chart.renderer.text('some Text', p.dataLabel.x + 150, p.dataLabel.y + chart.plotTop - bBox.y).add();
});
}
}
Live demo: https://jsfiddle.net/BlackLabel/w2cs4ufe/1/
API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#text

Highchart: is it possible to change the font of the label in Highchart via a click of a button?

Link to JFiddle: http://jsfiddle.net/z24ysp8m/3/
Here is the code in concern:
$(function() {
var chartData = [-5, 5, -10, -20];
var timeStamps = [];
var index = 1;
var pWidth = 25;
$('#b').click(function(){
timeStamps.push(new Date());
var buttonB = document.getElementById('b');
buttonB.disabled = true;
/* if(index == 1){
$('#container').highcharts().xAxis[0].labels.style = {"color":"#6D869F","fontWeight":"bold"};
}*/
if(index <= chartData.length){
$('#container').highcharts().series[0].remove();
$('#container').highcharts().addSeries({pointPlacement: 'on', data: [chartData[index - 1]],
pointWidth: pWidth});
$('#container').highcharts().xAxis[0].setCategories([index]);
setTimeout(function(){index++;}, 2000);
}
if(index < chartData.length){
setTimeout(function(){buttonB.disabled = false;}, 1500);
}else{
setTimeout(function(){buttonB.style.visibility="hidden";}, 1500);
}
if(index == chartData.length - 1){
setTimeout(function(){document.getElementById('b').innerHTML = 'Lasst Period';}, 1500);
}
console.log(timeStamps);
})
// $(document).ready(function () {
Highcharts.setOptions({
lang: {
decimalPoint: ','
},
});
$('#container').highcharts({
chart: {
type: 'column',
width: 170,
marginLeft: 74,
marginRight: 16,
marginBottom: 60
},
title: {
text: ''
},
colors: [
'#0000ff',
],
xAxis: {
title: {
text: ''
// offset: 23
},
gridLineWidth: 1,
startOnTick: true,
tickPixelInterval: 80,
categories: ['Filler'], // used only to make sure that the x-axis of the two charts
// are aligned, not shown on the chart via setting the font color to white
min:0,
max:0,
labels: {
style: {
color: 'white'
}
}
},
yAxis: {
title: {
text: 'Value'
},
min: -20,
max: 20,
tickPixelInterval: 40
},
plotOptions: {
series: {
animation: {
duration: 1000
}
}
},
credits: {
enabled: false
},
tooltip: {
formatter: function () {
return Highcharts.numberFormat(this.y, 2) + '%';
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
data: [],
pointWidth: pWidth
}]
});
// });
});
I want that the x-axis has no label when the page is loaded (The reason why I added in a filler text with white font is due to the fact that I don't want the size of the chart change upon click of a button). And upon the click of button, the label should be consecutively 1, 2, 3, 4...
Is there anyway around it except for setting marginBottom (which is not very precise)?
You may use .css() method for changing fill color of your text label.
Here you can find information about this method:
http://api.highcharts.com/highcharts#Element.css
Highcharts.each($('#container').highcharts().xAxis[0].labelGroup.element.children, function(p, i) {
$(p).css({
fill: 'red'
});
});
And here you can find simple example how it can work:
http://jsfiddle.net/z24ysp8m/6/

How to add data tables to dynamically generated highcharts

I want to add data tables to Charts.
I tried the implementation shown here: http://jsfiddle.net/highcharts/z9zXM/
but it didnt work for me.
I suspect its because how I instantiate highcharts.
in the example above the chart is generated by instantiating the Highcharts object.
my code:
// data from an ajax call
$.each(data, function(indicator, questions) {
indicator_type = "";
$.each(questions, function(question, value) {
dataChartType = "column";
series = [];
categories = [];
category_totals = {};
if(value.programs == null) {
return true;
}
$.each(value.programs, function(program, body) {
total = 0;
values = [];
$.each(body, function(j, k) {
if (categories.indexOf(j) == -1) {
categories.push(j);
category_totals[j] = 0;
}
if(k != 0) {
values.push(k);
} else {
values.push(null);
}
category_totals[j] += parseInt(k, 10);
total += k;
});
series.push({
data: values,
total: total,
name: program //question
});
}); // eo each program
var chartDiv = document.createElement('div');
chartDiv.className = "chart";
$('.charts_wrap').append(chartDiv);
$(chartDiv).highcharts({
events: {
load: Highcharts.drawTable
},
chart: {
type: dataChartType
},
xAxis: {
categories: categories
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'right',
verticalAlign: 'top',
y: 60,
x: -60
},
tooltip: {
formatter: function () {
return '<strong>' + this.series.name + '</strong><br/>' + this.x + ': ' + this.y;
}
},
plotOptions: {
line: {
connectNulls: true
},
column: {
stacking: 'normal',
dataLabels: {
enabled: false,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px w'
}
}
}
},
series: series,
title:{ text: indicator },
subtitle:{ text: question }
});
}); // EO each question
}); // eo each indicator
When instantiating highcharts like this:
$("#container").highcharts({ ...
The events option needs to be included inside the charts option:
$("#container").highcharts({
chart: {
type: 'column',
events: {
load: Highcharts.drawTable
},
},
...

Highcharts Bar Chart: possible to combine datapoints inside dataLabels?

I have a Highcharts horizontal bar chart with two series. Is it possible to combine the grouped data points into each data label so that they appear together, e.g. 1.00 / 2.3?
CODE:
var labels = [
'AAA/Aaa',
'AA+/Aa1',
'AA/Aa2',
'AA-/Aa3',
'A+/A1',
'A/A2',
'A-/A3'
];
var theData = [
{
name: 'Company 1',
data: [0.576,7.617,12.101,18.839,18.022,7.644,9.72]
},
{
name: 'Company 2',
data: [4.123,12.862,14.561,13.754,12.226,11.135,7.51]
}
];
HIGHCHARTS CONFIG:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
legend: {
align: 'center',
layout: 'horizontal',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function() {
var out = '<span class="col-chart-label">';
out += this.y + ' / ' + this.y;
out += '</span>'
return out;
},
useHTML: true
}
}
},
series: theData,
tooltip: {
enabled: false
},
xAxis: {
categories: labels,
labels: {
formatter: false,
overflow: 'justify',
rotation: false
},
reversed: true
}
});
});
The demo is here:
http://jsfiddle.net/dylanmac/RungW/2/
To reiterate, there should be one data label per pair of bars with the top bar as the first value and the bottom bar as the second value, separated by "/"
Thanks a lot.
You can loop through all series and sum values for a specific category, see: http://jsfiddle.net/RungW/3/
formatter: function() {
var out = '<span class="col-chart-label">',
series = this.point.series.chart.series,
p1 = series[0].yData[this.point.x],
p2 = series[1].yData[this.point.x];
out += this.y + ' / ' + (p1 + p2);
out += '</span>'
return out;
},

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

Categories

Resources