简体   繁体   中英

How to hide bar but keep datalabels HighCharts

How to hide bar but keep datalabels HighCharts , i have 3 bars,

  1. Target
  2. Realization
  3. Percentage


i supposed to show only the first and the second bar,with only 1 datalabels which is percentage. so i made quite a trick to my code
Here is the sample :

var target = [50,100];
var realization = [10,40];
var percentage = [];

for(i = 0;i < target.length; i++) {
  var divide = (realization[i] / target[i]) * 100;
  if (divide == Number.POSITIVE_INFINITY || divide == Number.NEGATIVE_INFINITY || isNaN(divide)) {
    percentage.push(0);
  } else {
    percentage.push(divide);
  }
}
series: [
    {
      name: 'Target )',
      color :' #009933',
      data: target,

    },
    // i put the trick on the second series where i tricked it
    {
      name: 'Percentage',
      data: percentage,
      color :'rgba(255, 255, 255, .4)',
      showInLegend: false,
      pointWidth :1, 
      lineColor: 'transparent',
      marker: { 
        fillColor: 'transparent',
        states: {
          hover: {
              enabled: false
          }
        }    
      }
    },
    {
      name: 'Realization',
      color : '#00ff00',
      data: percentage,
    }]

it will look like this 在此输入图像描述 The trick i used is make the percentage on the middle,and change the bar color into transparent.
This is the result i was expecting 在此输入图像描述
This is my full code :
https://jsfiddle.net/xanrdswq/
This is only temporary solution i have.

It can be simply achieved using Highchart.SVGRenderer.text method that allows drawing a custom text. Labels can be added in render event callback or chart callback (when the chart width is fixed).

Check code and demo posted below and let me know if something is not clear for you.

Code:

chart: {
  type: 'bar',
  events: {
    render: function() {
      const chart = this,
        xAxis = chart.xAxis[0],
        yAxis = chart.yAxis[0],
        offsetX = 5;

      let customElems = chart.customElems || [],
        y,
        x,
        element;

      if (customElems.length) {
        customElems.forEach(elem => {
          elem.destroy();
        });

        customElems.length = 0;
      }

      chart.series[0].points.forEach((point, i) => {
        x = yAxis.toPixels(point.y) + offsetX;
        y = xAxis.toPixels(point.x);

        element = chart.renderer.text(`${percentage[i]} %`, x, y).css({
          fill: '#000'
        }).add().toFront();

        customElems.push(element);
      });

      chart.customElems = customElems;
    }
  }
}

Demo:

API reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM