是否可以根据值定位Highcharts dataLabels?

3rg*_*rgo 13 javascript highcharts

我正在使用Highcharts来显示一个条形图,其中2个条形图相互重叠,右边有一个dataLabel,显示确切的值.

这里的问题是当值超过80%时,标签会从图表溢出到框架中,翻过其他文本,并使它们都不可读.

这是我的plotOptions:

plotOptions: {
            bar: {
                groupPadding: 0.5,
                pointWidth : 30,
                borderWidth: 0,
                dataLabels: {
                    enabled: true,
                    y:-5,
                    color:"black",
                    style: {
                        fontSize: "12px"
                    },
                    formatter: function(){
                        if(this.y > 80)
                        {
                            this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;
                        }
                        if(this.series.name == "Tests OK")
                            return "Tests OK : <strong>"+Math.round(this.y*10)/10+"%</strong>";
                        else
                            return "<br/>Tests Executed : <strong>"+Math.round(this.y*10)/10+"%</strong>";
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

我想我可以随时随地编辑图表选项this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;,但这不起作用.

当然,我不是第一个遇到类似问题的人.任何的想法 ?

谢谢

Bhe*_*ung 14

看起来不可能从内部做到这一点formatter.

但是您可以在渲染(加载)图表后设置它们.尝试这样的事情

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

load callback(或如果你需要它redraw callback).

这里的例子.


jve*_*ema 5

这就是我最终的结果.必须使用setTimeout或者该点上不存在dataLabel属性:

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>';
}
Run Code Online (Sandbox Code Playgroud)