Forum Discussion

Ophir_Buchman's avatar
Ophir_Buchman
Data Integration
04-20-2022

Bar Chart - Add Percentage to the Value Label

When creating a column chart you might want to add a percentage value next to the actual value

Add the following script to your widget:

widget.on('processresult', function(widget,result) { 
result.result.plotOptions.series.dataLabels.formatter = function() {
total = 0
this.series.data.forEach(function(datapoint) { total += datapoint.y })

percent = (100 * this.y) / (total);
percent = percent.toFixed(1);

return this.y + '<br/>(' + percent + '%)'
}
})
Before After

3 Replies

Replies have been turned off for this discussion
  • dbailey's avatar
    dbailey
    Data Storage

    Thank you for producing this code.  This is a feature I have been trying to figure out for a while.  Can you please provide some additional detail? I am a user with minimal script/coding experience.  Is this script inserted into the script editor or directly into the sql code for the widget?  Also, are there variables within this code that need to be changed for the specific widget data it is inserted into?  Thank you.

    • zach_myt's avatar
      zach_myt
      Data Pipeline

      dbailey You paste that code into the edit script section of the widget once you click the 3 dots.

       

      Although I am getting percentages that do not match the hover. Any ideas on why I am getting different percentages? Ophir_Buchman 

       

       

       

  • zach_myt's avatar
    zach_myt
    Data Pipeline

    I found another way to add it if you just want the percentage, just use "this.percentage", and define your decimal points.

     
     
    widget.on('processresult', function(se, ev) {
    //display the percentage on the bar
        ev.result.series.forEach(category => {
            category.dataLabels = {
                enabled: true,
                style: {
                    fontSize: '12px',
    fontWeight: 'Bold'
                },
                formatter: function() {
                    if (this.y !== 0) {
    return this.percentage.toFixed(2) + '%';
                    } else {
                        return null;
                    }
                }
            };
        });
    });