简体   繁体   中英

How to render a line from dataLabels to marker on graph in HighCharts?

I have a HighCharts spline graph with data labels appearing above the points. I would like to have a line drawn from the label to the point on the graph, to help the user see what the label corresponds to.

See example here: http://jsfiddle.net/wa0jej56/

The code is:

Highcharts.chart('container', {
    xAxis: {
        minPadding: 0.05,
        maxPadding: 0.05
    },
    plotOptions: {
        series: {
            dataLabels: {
                enabled: true,
                format: '{point.name}',
                y: -20,
                allowOverlap: true,
                useHTML: true
            }
        },
    },
    series: [{
        data: [
            {name: 'First', x: 0, y: 29.9},
            {name: 'Second <br>&nbsp;', x: 0.1, y: 29.9},
            {name: 'Third', x: 1, y: 1.5},
            {name: 'Fourth', x: 2, y: 106.4}
        ]
    }]
});

Note that I can't put the labels directly on the points, because sometimes labels overlap each other, and I have to stagger them vertically.

You need to set data label's shape. The only available shape which points to the point is callout but it much different than just a connecting line.

You need to define your own shape:

Highcharts.SVGRenderer.prototype.symbols.connector = function(x, y, w, h, options) {
  var anchorX = options && options.anchorX,
      anchorY = options && options.anchorY,
      path,
      yOffset,
      lateral = w / 2,
      H = Highcharts;

  if (H.isNumber(anchorX) && H.isNumber(anchorY)) {

    path = ['M', anchorX, anchorY];

    // Prefer 45 deg connectors
    yOffset = y - anchorY;
    if (yOffset < 0) {
      yOffset = -h - yOffset;
    }
    if (yOffset < w) {
      lateral = anchorX < x + (w / 2) ? yOffset : w - yOffset;
    }

    // Anchor below label
    if (anchorY > y + h) {
      path.push('L', x + lateral, y + h);

     // Anchor above label
    } else if (anchorY < y) {
      path.push('L', x + lateral, y);

    // Anchor left of label
    } else if (anchorX < x) {
      path.push('L', x, y + h / 2);

    // Anchor right of label
    } else if (anchorX > x + w) {
      path.push('L', x + w, y + h / 2);
    }
  }
  return path || [];
};

And then use it as a shape in data labels config;

      dataLabels: {
    shape: 'callout',
    enabled: true,
    format: '{point.name}',
    y: -20,
    allowOverlap: true,
    borderWidth: 1,
    borderColor: 'black',
    useHTML: true
  }

example: http://jsfiddle.net/02fvu3d6/

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