首页 > 解决方案 > 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 thisenter image description here The trick i used is make the percentage on the middle,and change the bar color into transparent.
This is the result i was expectingenter image description here
This is my full code :
https://jsfiddle.net/xanrdswq/
This is only temporary solution i have.

标签: javascriptjsonhighcharts

解决方案


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:


推荐阅读