如何检测数据标签何时重叠并以编程方式调整它们

How to detect when dataLabels are overlapping and adjust them programmatically

我有一个堆叠式 column/scatter 图表,其中一些数据标签偏向一侧。我面临的问题是,当我的两个标记开始相互靠近时,它们的数据标签重叠

我需要始终显示两个标签,那么有没有一种方法可以检测标签何时重叠并根据重叠程度调整其 y 值来向下移动底部标签?

sample fiddle of the issue

Highcharts.chart('container', {
  chart: {
    type: 'column',
    width: 500
  },
  title: {
    text: 'Stacked column chart'
  },
  xAxis: {
    visible: false,
  },
  yAxis: {
    min: 0,
    visible: false,
    title: {
    },
    
    
  },
  legend: {
    layout:"vertical",
    align: "right",
    verticalAlign: "bottom",
    itemMarginTop: 15,
    y: -10,
    x: -50
  },
  tooltip: {
    enabled: false,
  },
  plotOptions: {
    scatter: {
      marker: {
        symbol: "triangle",
      },
      dataLabels: {
        enabled: true,
        x: -80,
        y: 50,     
        allowOverlap: true,
        useHTML: true,
      }
    },
    column: {
      pointWidth: 70,
      stacking: 'normal',
      dataLabels: {
        enabled: false
      }
    }
  },
  series: [{
    name: '',
    data: [100],
    color: "#ededed"
  }, {
    name: '',
    data: [500]
  }, {
    name: '',
    data: [400]
  },
          {
            type: "scatter",
            data: [1000],
            color: "#000",
            dataLabels: {
            formatter: function(){
              return "<div class='label-text'>Your goal of <br/>$"+ this.y +"<br/>text</div>"
            },
            }
          
          },
          {
            type: "scatter",
            data: [900],
            color: "#000",
            dataLabels: {
            formatter: function(){
              return "<div class='label-text'>You are here <br/>$"+ this.y +"<br/>text</div>"
            },
            }
          }]
});

您可以通过在其 SVG 元素上使用 attr 方法来更正 data-labels 位置。

例如:

  chart: {
    events: {
      render: function() {
        const series = this.series;
        const dl1 = series[3].points[0].dataLabel;
        const dl2 = series[4].points[0].dataLabel;

        if (dl1.y + dl1.height > dl2.y) {
          dl2.attr({
            y: dl1.y + dl1.height
          });
        }
      }
    }
  }

现场演示: https://jsfiddle.net/BlackLabel/5Lmh4owb/

API参考:

https://api.highcharts.com/class-reference/Highcharts.SVGElement.html#attr

https://api.highcharts.com/highcharts/chart.events.render