Can highcharts xrange labels be shown only if they fit the box?

778 Views Asked by At

I would like to create a Highcharts xrange chart where only data labels that fit into boxes/ranges are shown. Is this possible?

At the moment, labels don't overlap but are shown outside the box when they don't fit.

I tried playing with the xrange.dataLabels options like 'allowOverlap','clip, 'inside' or 'padding' but they don't seem to be created to do this/work.

Example is shown here: http://jsfiddle.net/mdomnita/dfLw7j1c/1/

Highcharts.chart('container', {
chart: {
    type: 'xrange'
},
title: {
    text: 'Highcharts X-range'
},
xAxis: {
    type: 'datetime'
},
yAxis: {
    title: {
        text: ''
    },
    categories: ['Idea','Prototyping'],
    reversed: true
},
series: [{
    name: 'Project 1',
    data: [{
        x: Date.UTC(2014, 10, 21),
        x2: Date.UTC(2014, 11, 2),
        y: 0
    }, {
        x: Date.UTC(2014, 11, 10),
        x2: Date.UTC(2014, 11, 11),
        y: 1
    }, {
        x: Date.UTC(2014, 11, 11),
        x2: Date.UTC(2014, 11, 12),
        y: 1
    }],
    dataLabels: {
        enabled: true,
        formatter: function () {
          return 'This is a label that should only be shown if it fits the box'
        },
    }
}]
});

Thanks,

1

There are 1 best solutions below

0
On BEST ANSWER

You can easy implement required behavior, for example in render event, in this way:

    events: {
        render: function() {
            var points = this.series[0].points;

            Highcharts.each(points, function(point) {
                var label = point.dataLabel;

                if (point.shapeArgs.width < label.width) {
                    if (label.visibility !== 'hidden') {
                        label.hide();
                    }
                } else {
                    if (label.visibility === 'hidden') {
                        label.show();
                    }
                }
            });
        }
    }

Live demo: http://jsfiddle.net/BlackLabel/k4swecd6/