[Solved] How can i create Highchart xAxis labels centered and enclosed?


I would use Highcharts.SVGRenderer to draw rect elements, based on the ticks from the second xAxis and translate the labels. Please check the example below:

chart: {
    events: {
        render: function() {
            var ticks = this.xAxis[1].ticks,
                x = this.plotLeft,
                y = 378,
                width,
                color="blue",
                textColor="yellow",
                height = 28;

            if (!this.customTicks) {
                this.customTicks = [];
            } else {
                this.customTicks.forEach(function(cTick) {
                    cTick.destroy();
                });
                this.customTicks.length = 0;
            }

            Highcharts.objectEach(ticks, function(tick) {
                if (tick.mark) {

                    width = tick.mark.getBBox().x - x;
                    tick.label.element.children[0].setAttribute('fill', textColor);
                    tick.label.attr({
                        translateX: -width / 2
                    });

                    this.customTicks.push(
                        this.renderer.rect(
                            x,
                            y,
                            width,
                            height
                        ).attr({
                            fill: color
                        }).add()
                    )

                    x = tick.mark.getBBox().x;
                    if (color === 'blue') {
                        color="gray";
                        textColor="white";
                    } else {
                        color="blue";
                        textColor="yellow";
                    }
                }

            }, this)

            this.customTicks.push(
                this.renderer.rect(
                    x,
                    y,
                    this.xAxis[1].width + this.plotLeft - x,
                    height
                ).attr({
                    fill: color
                }).add()
            )

        }
    }
}

Live demo: https://jsfiddle.net/BlackLabel/s7vfkgzt/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#rect

13

solved How can i create Highchart xAxis labels centered and enclosed?