change dataLabels based on color of bar - Javascript highcharts

Javascript examples for highcharts:Bar Chart

Description

change dataLabels based on color of bar

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <style>

.highcharts-button-box{
   fill: #00599a;
}
.highcharts-button tspan{
   fill: white//from  ww w  .j a  v a2 s .co  m
}


      </style> 
   </head> 
   <body translate="no"> 
      <div id="container"></div> 
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.7/highcharts.js"></script> 
      <script>
      var perShapeGradient = {
        x1: 0,
        y1: 0,
        x2: 1,
        y2: 0
    };
var data = [{
      name: 'char 1',
      y: 1756,
      fontWeight: 'bold',
      //color: 'green'
    },{
      name: 'char 2',
      y: 512,
      fontWeight: 'bold',
    },{
      name: 'char 3',
      y: 756,
      fontWeight: 'bold',
    }]
var dataSum = data.reduce((a,x)=>a+x.y,0);
Highcharts.chart('container', {
  chart: {
    type: 'bar',
    backgroundColor: null,
    height: 216,
    events: {
       load: function() {
         this.update({
           plotOptions: {
              series: {
                 dataLabels: {
                   formatter:function() {
                      var pcnt = (this.y / dataSum) * 100;
                      return '<tspan style="color:' + this.point.color + '">' + Highcharts.numberFormat(pcnt) + '%' + '</tspan>';
                  }}
              }
           }
         });
       }
    }
  },
  title: {
    text: ''
  },
  xAxis: {
    type: 'category',
    labels: {
        style: {
            fontWeight: 'bold'
        }
    }
  },
  colors: [{
    linearGradient: perShapeGradient,
    stops: [
      [0, '#c2352b'],
      [1, '#f44336 ']
    ]
  }, {
    linearGradient: perShapeGradient,
    stops: [
      [0, '#1b75bf'],
      [1, '#2196f3']
    ]
  }, {
    linearGradient: perShapeGradient,
    stops: [
      [0, '#cc7a00'],
      [1, '#ff9800']
    ]},
          ],
  yAxis: {
    title: {
      text: ''
    },
  },
  credits: {
      enabled: false
  },
  legend: {
    enabled: false
  },
  plotOptions: {
    series: {
      borderWidth: 0,
      pointPadding: 0.12,
      groupPadding: 0,
      dataLabels: {
        enabled: true
      },
      colorByPoint: true
    }
  },
  tooltip: {
    headerFormat: '<span style="font-size:11px"> Jumlah Suara</span><br>',
    pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.f} Suara</b><br/>'
  },
  series: [{
        data: data
    }
          ]
});
    
      </script>  
   </body>
</html>

Related Tutorials