Change bar chart data label position - Javascript highcharts

Javascript examples for highcharts:Bar Chart

Description

Change bar chart data label position

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="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <script type="text/javascript">
$(function() {/*from  w ww  .j  a  v  a 2 s.  com*/
  var rawData = [7, 14, 16, 5, 4],
    data = [
      [0, 100]
    ],
    overData = [
      [0, 0]
    ],
    zones = [],
    len = rawData.length,
    colors = Highcharts.getOptions().colors,
    maxColor = colors.length,
    i, val, sum = 0,
    pos = 0;
  for (i = 0; i < len; i++) {
    sum += rawData[i];
  }
  for (i = 0; i < len; i++) {
    pos += rawData[i];
    val = (sum - pos) / sum * 100;
    data.push([pos, val]);
    overData.push([pos, (100 - val) / 2]);
    zones.push({
      value: pos,
      color: colors[i % maxColor]
    });
  }
  const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
  function drawLabels() {
    const zonesLabels = this.zonesLabels
    const series = this.get('s1')
    const { yAxis, xAxis } = series
    const y = yAxis.toPixels(0)
    series.zones.reduce((prev, curr, i) => {
      if (curr.value !== undefined) {
        const x = (xAxis.toPixels(prev.value) + xAxis.toPixels(curr.value)) / 2
        if (!zonesLabels[i]) {
          zonesLabels.push(
            this.renderer.label(labels[i], x, y - 20).add().attr({
              align: 'center',
              zIndex: 10
            })
          )
        } else {
          zonesLabels[i].attr({ x, y })
        }
      }
      return curr
    }, {
      value: series.dataMin
    })
  }
  $('#container').highcharts({
    chart: {
      type: 'area',
      events: {
        load: function() {
          this.zonesLabels = []
          drawLabels.call(this)
        },
        redraw: drawLabels
      }
    },
    yAxis: {
      title: {
        text: 'Percent'
      }
    },
    plotOptions: {
      area: {
        enableMouseTracking: false,
        showInLegend: false,
        stacking: 'percent',
        lineWidth: 0,
        marker: {
          enabled: false
        }
      }
    },
    series: [{
      name: 'over',
      color: 'none',
      data: overData
    }, {
      id: 's1',
      name: 'Series 1',
      data: data,
      showInLegend: true,
      zoneAxis: 'x',
      zones: zones
    }]
  });
});

      </script> 
   </head> 
   <body> 
      <script src="https://code.highcharts.com/highcharts.js"></script> 
      <script src="https://code.highcharts.com/modules/exporting.js"></script> 
      <div id="container" style="min-width: 310px; height: 400px; max-width: 800px; margin: 0 auto"></div>  
   </body>
</html>

Related Tutorials