Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

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

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 is that when the value is above 80%, the label is overflowing from the chart into the frame, going over some other text, and making them both unreadable.

Here are my 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>";
                    }
                }
            }
        }

I thought i could edit the chart options on the go, using this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;, but this doesn't work.

Surely I'm not the first one who has encountered a problem like that. Any idea ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...