HighCharts。如何动态设置刻度并相对于标签中的文本显示标签?

问题描述 投票:0回答:2

我通过tickPositioner动态设置了刻度,并通过labels.formatter设置了标签。屏幕宽度较窄,我需要显示较少的刻度和标签,以便所有内容都适合。

我想获取标签的宽度。这样我就可以计算出步骤。

https://jsfiddle.net/Lnbaqwce/ enter image description here

Highcharts.chart('container', {

  chart: {
    events: {
      render() {
            var ticks = this.xAxis[0].ticks,
                ticksPositions = this.xAxis[0].tickPositions,
                tick0x,
              tick1x,
              getPosition = function (tick) {
                var axis = tick.axis;
                return Highcharts.Tick.prototype.getPosition.call(tick, axis.horiz, tick.pos, axis.tickmarkOffset);
              };

          tick0x = getPosition(ticks[ticksPositions[0]]).x;
          tick1x = getPosition(ticks[ticksPositions[1]]).x;

          this.xAxis[0].labelGroup.translate((tick1x - tick0x) / 12)
            }
    }
  },
  xAxis: {
    min: 0,
    max: 20,
    tickPositioner: function () {
      var positions = [],
          tick = Math.floor(this.dataMin),
          increment = Math.ceil((this.dataMax - this.dataMin) / 6);

      if (this.dataMax !== null && this.dataMin !== null) {
        for (tick; tick - increment <= this.dataMax; tick += increment) {
          positions.push(tick);
        }
      }
      return positions;
    },
    labels: {
        formatter: function() {
        return this.value + "%$$$";
      }
    }
  },
  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 100.20, 200.30]
  }]
});
javascript highcharts
2个回答
0
投票

这是一个示例,该示例如何获取可在计算中使用的标签宽度。

if(this.ticks[tick]) {
  console.log(this.ticks[tick].label.getBBox().width)
}

演示:https://jsfiddle.net/BlackLabel/15msykgw/


0
投票

代替在tickPositioner中进行这些计算,我认为更好的解决方案是:

  1. 获得最宽的标签宽度,
  2. 将轴宽除以标签宽度以上,
  3. 使用从上方输出的输出对轴进行更新

    function(chart){
    let xAxis = chart.xAxis[0],
        labelWidth = xAxis.ticks[10].label.getBBox().width, // I choose tick 10 
        because is more wide
        axisWidth = xAxis.width,
        tickAmount = axisWidth / labelWidth;
    
        xAxis.update({
            tickAmount: tickAmount
        });
    }
    

演示:https://jsfiddle.net/BlackLabel/duegno8z/1/API:https://api.highcharts.com/highcharts/xAxis.tickAmount

© www.soinside.com 2019 - 2024. All rights reserved.