Bar Chart - Prevent bars from hiding the value label text
When creating a bar chart and formatting it to include "Values", you might find out that the bars cover their values. The following (widget) code manipulates the bars' width and label position:
const labelWidth = 25 + 5 // 5 is the space between the label and the bar
widget.on('domready', function(widget) {
try {
console.log('DOM Ready script starting (wid=' + widget.oid + ')');
// Get plot width
plotWidth = parseInt(widget.chart[0].getElementsByClassName('highcharts-plot-border')[0].getAttribute('width'));
// Find Widest bar
maxBarWidth = -1;
widget.chart[0].getElementsByClassName('highcharts-series','highcharts-bar-series').forEach(bar => {
bar.childNodes.forEach(rect => {
if (parseInt(rect.getAttribute('height')) > maxBarWidth)
maxBarWidth = parseInt(rect.getAttribute('height'))
})
})
if (maxBarWidth == -1) return;
// Check if we require adjustment
if (plotWidth - maxBarWidth > labelWidth) return;
ratio = (maxBarWidth - labelWidth) / maxBarWidth;
// Adjust Bar height and location
barsArray = widget.chart[0].getElementsByClassName('highcharts-series','highcharts-bar-series');
labelsArray = widget.chart[0].getElementsByClassName('highcharts-data-labels');
for (let seriesNum = 0; seriesNum < barsArray.length; seriesNum++) {
for (let barNum = 0; barNum < barsArray[seriesNum].childNodes.length; barNum++) {
currentWidth = parseInt(barsArray[seriesNum].childNodes[barNum].getAttribute('height'));
currentY = parseInt(barsArray[seriesNum].childNodes[barNum].getAttribute('y'));
transformLabel = labelsArray[seriesNum].childNodes[barNum].getAttribute('transform')
// Calculate offset
offset = Math.round(currentWidth * (1-ratio))
// Adjust bars
barsArray[seriesNum].childNodes[barNum].setAttribute('height',currentWidth-offset)
barsArray[seriesNum].childNodes[barNum].setAttribute('y',currentY+offset)
// Adjust labels
newLabel = 'translate(' + (currentWidth - offset) + ',' + transformLabel.split(',')[1]
labelsArray[seriesNum].childNodes[barNum].setAttribute('transform',newLabel)
}
}
}
catch (error) {
console.error(error);
}
finally {
console.log('DOM Ready script complete (wid=' + widget.oid + ')');
}
});
Before | After |
Updated 03-25-2022
Ophir_Buchman
Data Integration
Joined October 19, 2021