highcharts 如何检测dataLabel何时重叠并以编程方式调整它们

bpzcxfmw  于 2022-11-10  发布在  Highcharts
关注(0)|答案(1)|浏览(234)

我有一个堆叠柱形图/散点图,其中一些dataLabels偏离到一侧。我面临的问题是,当我的两个标记开始彼此接近时,它们的dataLabels重叠
我需要始终显示两个标签,那么是否有一种方法可以检测标签重叠的情况,并根据重叠的程度调整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>"
            },
            }
          }]
});
eyh26e7m

eyh26e7m1#

您可以在数据标签的SVG元素上使用attr方法来更正数据标签的位置。
例如:

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

相关问题