cancel
Showing results for 
Search instead for 
Did you mean: 

Bar Chart - Add Percentage to the Value Label

Ophir_Buchman
Sisense Team Member
Sisense Team Member

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
Ophir_Buchman_0-1650452574643.png Ophir_Buchman_1-1650452595480.png
3 REPLIES 3

dbailey
7 - Data Storage
7 - 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.

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

zach_myt_0-1704297341918.png

 

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

zach_myt_2-1704297516630.png

 

 

 

zach_myt
10 - ETL
10 - ETL

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