Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highcharts percentage of total for simple bar chart

I have a simple 1-series bar chart where each bar has a nominal value. I can plot this fine with the data labels and axis representing the value for each bar but I'd like to have the data label and axis show the percentage of the total of the series while the nominal value is shown in a tooltip on hover (thus I don't want to convert the data to percentages prior to plotting).

Here is an image showing what I'm after and where I am now:

fiddle

enter image description here

Here's what I currently have for axis labels as the formatter function:

plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true,
                    formatter: function(){
                        return Highcharts.numberFormat(this.y,0);
                    }
                }
            }
        }

Is there some formatter function variable I can use to achieve this? I know it is easily done on a pie chart but I feel bar charts represent data much better.

EDIT: To put it simply, how do I get the sum of all the series' points? Once I have this it is straightforward to get the percentage:

return Highcharts.numberFormat(100 * this.y / this.y.total,0) + "%";

where this.y.total is the sum of the series.

like image 309
harryg Avatar asked May 30 '13 13:05

harryg


1 Answers

@jlbriggs had a great answer and lead me onto the path of creating this formatter function. This function always checks the current values in the data. If the data is updated programmatically at a later time, the percentages will reflect the newly updated data. No dataSum or loop is necessary as the .map().reduce() takes care of that for you.

dataLabels: {
  enabled: true,
  formatter: function() {
    var pcnt = (this.y / this.series.data.map(p => p.y).reduce((a, b) => a + b, 0)) * 100;
    return Highcharts.numberFormat(pcnt) + '%';
  }
}
like image 171
strikemike2k Avatar answered Sep 21 '22 20:09

strikemike2k