如何创建居中和封闭的Highchart xAxis标签?

时间:2019-01-26 01:37:44

标签: highcharts

我正在尝试在图像上复制效果,但是没有运气。在另一篇文章中,有人回答了如何实现多条轴线(请参见结尾处的链接),但我无法实现样式(灰色和蓝色框中的最大宽度标签)。multiline styled axis labels in highchart

上一篇文章:Highcharts: How can I achiveve multiple rows on chart labels?

1 个答案:

答案 0 :(得分:0)

我将根据第二个Highcharts.SVGRenderer的刻度线,使用rect绘制xAxis元素并翻译标签。请检查以下示例:

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()
            )

        }
    }
}

实时演示:https://jsfiddle.net/BlackLabel/s7vfkgzt/

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