I'm generating a bar chart and currently all data labels are aligned to the right.
For positive values, I would like the data label aligned to the right of the bar and for negative values I would like the data label aligned to the left of the bar.
How can I achieve this?
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
xAxis: {
categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania']
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
align: 'right',
inside: true
}
}
},
series: [{
data: [107, 31, 635, -203, -300]
}]
});
});
There are probably quite a few ways to do this. One way is setting point specific dataLabels
objects. Depending on the size of your data this could be done directly on the series data, like this (JSFiddle):
series: [{
data: [107, 31, 635, { y: -203, dataLabels: { align: 'left' } }, { y: -300, dataLabels: { align: 'left' } }]
}]
Or you could for example use the callback function when initializing the chart to loop over your series and set it in the same way, like this (JSFiddle):
$('#container').highcharts({
series: [{
data: [107, 31, 635, -203, -300]
}]
// ...
}, function() {
for(var i = 0; i < this.series.length; i++) {
for(var j = 0; j < this.series[i].points.length; j++) {
var point = this.series[i].points[j];
if(point.y < 0) {
point.update({ dataLabels: { align: 'left'} }, false);
}
}
}
this.redraw();
});
An alternative approach which I will only describe is using several series, one for positive and one for negative, and then link them and use different align
specifications for each series.