我通过tickPositioner动态设置了刻度,并通过labels.formatter设置了标签。屏幕宽度较窄,我需要显示较少的刻度和标签,以便所有内容都适合。
我想获取标签的宽度。这样我就可以计算出步骤。
https://jsfiddle.net/Lnbaqwce/
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]
}]
});
这是一个示例,该示例如何获取可在计算中使用的标签宽度。
if(this.ticks[tick]) {
console.log(this.ticks[tick].label.getBBox().width)
}
代替在tickPositioner中进行这些计算,我认为更好的解决方案是:
使用从上方输出的输出对轴进行更新
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