Is it possible to position Highcharts dataLabels depending on the value?

后端 未结 4 480
温柔的废话
温柔的废话 2020-12-14 11:32

I\'m using Highcharts to display a bar chart, with 2 bars overlaying each other, and a dataLabels at the right of them, displaying the exact value.

The problem here

相关标签:
4条回答
  • 2020-12-14 12:01

    I've been trying to figure some of this out myself... it looks like instead of

    this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;
    

    could you use...

    this.series.options.dataLabels.x = -20;
    

    ... at this point I'm trying to understand if I'm able to discern the location of a dataLabel so that I can reposition it if necessary.

    0 讨论(0)
  • 2020-12-14 12:06

    Here's what I ended up with. The setTimeout is necessary or the dataLabel property doesn't exist on the point:

    formatter: function () {
        var point = this.point;
        window.setTimeout(function () {
            if (point.s < 0) {
                point.dataLabel.attr({
                    y: point.plotY + 20
                });
            }
        });
        //this.series.options.dataLabels.y = -6;
        var sty = this.point.s < 0 ? 'color:#d00' : 'color:#090;' //other style has no effect:(
        return '<span style="' + sty + '">' + Math.abs(this.point.s) + '</span>';
    }
    
    0 讨论(0)
  • 2020-12-14 12:13

    Looks like it's not possible to do that from within the formatter.

    But you could set them after the chart is rendered (loaded). Try something like this

    $.each(chartObj.series[0].data, function(i, point) {
        if(point.y > 100) {
            point.dataLabel.attr({x:20});
        }
    });
    

    in the load callback (or if you need it in the redraw callback).

    See example here.

    0 讨论(0)
  • 2020-12-14 12:15

    Although Bhesh's answer solves the problem for x/y positioning, Highcharts ignores any changes to the style property of dataLabels (see the problem here). However, you can override the styles of an individual point by passing it through the data object:

    series: [{ data: [29.9, 106, { y: 135, dataLabels: { style: { fontSize: 20 } } }]
    

    example from Highcharts docs

    I was able to get dynamic styles by iterating over my data before passing the whole object to Highcharts to render.

    0 讨论(0)
提交回复
热议问题