JAPANTHR
JAPANTHR

Reputation: 15

How to detect when dataLabels are overlapping and adjust them programmatically

I have a stacked column/scatter chart with some dataLabels off to one side. The issue I am facing is that when my two markers begin to get close to one another, their dataLabels overlap

I need to always show both labels, so is there a way to detect when labels are overlapping and move the bottom one down by adjusting its y value based on how much overlap there is?

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>"
            },
            }
          }]
});

Upvotes: 0

Views: 942

Answers (1)

ppotaczek
ppotaczek

Reputation: 39139

You can correct data-labels positions by using the attr method on their SVG elements.

For example:

  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
          });
        }
      }
    }
  }

Live demo: https://jsfiddle.net/BlackLabel/5Lmh4owb/

API Reference:

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

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

Upvotes: 2

Related Questions