Change datalabel position when value is too small - Javascript highcharts

Javascript examples for highcharts:Chart Value

Description

Change datalabel position when value is too small

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <script type="text/javascript">
var innerPadding = 2;// www  .j  a v  a2 s.c  o  m
function realignLabels(serie) {
    var chart = serie.chart;
    var borderWidth = chart.options.plotOptions.bar.borderWidth;
    $.each(serie.points, function(j, point) {
        if (!point.dataLabel) return true;
        var xCoord = point.dataLabel.x;
        if (point.y < 0) {
            if (point.barH <= point.dataLabel.width + (innerPadding * 2)) {
                xCoord += innerPadding + (borderWidth * 2) + 8;
            } else {
                xCoord += point.dataLabel.width + (innerPadding * 2) + (borderWidth * 2) + 8;
            }
        } else if (point.barH <= point.dataLabel.width + (innerPadding * 2)) {
            xCoord += point.dataLabel.width + innerPadding + (borderWidth * 2);
        }
        point.dataLabel.attr({
            x: xCoord
        });
    });
}
$(function () {
    Highcharts.Series.prototype.drawDataLabels = (function (func) {
        return function () {
            func.apply(this, arguments);
            if (this.options.dataLabels.enabled || this._hasPointLabels) realignLabels(this);
        };
    } (Highcharts.Series.prototype.drawDataLabels));
    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'bar'
        },
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
        },
        plotOptions: {
            series: {
                dataLabels: {
                    align: 'right',
                    enabled: true,
                    x: -innerPadding,
                    style: {
                        color: 'red'
                    }
                }
            }
        },
        series: [{
            data: [129.9, 171.5, 10, -10, -30, -200]
        }]
    });
});

      </script> 
   </head> 
   <body> 
      <script src="https://code.highcharts.com/highcharts.src.js"></script> 
      <div id="container" style="height: 400px"></div>  
   </body>
</html>

Related Tutorials