You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ChartJS折线图自定义Y轴刻度:仅显示两个指定位置文本标签

ChartJS Y轴自定义双标签配置方法

直接操作折线图配置项内的scales.y字段即可实现需求,具体配置逻辑和示例如下:

  • 核心是通过afterBuildTicks回调覆盖Y轴默认生成的刻度数组,仅保留25%、75%两个位置的刻度
  • 再通过ticks.callback自定义两个位置的显示文本

完整配置示例

const lineChartOptions = {
  scales: {
    y: {
      // 可选配置:隐藏刻度线、多余网格线
      grid: {
        drawTicks: false
      },
      // 动态计算刻度位置,覆盖默认刻度
      afterBuildTicks: (yAxis) => {
        const valRange = yAxis.max - yAxis.min;
        const pos25Val = yAxis.min + valRange * 0.25;
        const pos75Val = yAxis.min + valRange * 0.75;
        yAxis.ticks = [
          { value: pos25Val },
          { value: pos75Val }
        ];
      },
      ticks: {
        // 自定义刻度显示文本
        callback: function (currentVal) {
          const valRange = this.max - this.min;
          const pos25Val = this.min + valRange * 0.25;
          const pos75Val = this.min + valRange * 0.75;
          if (currentVal === pos25Val) return 'less';
          if (currentVal === pos75Val) return 'more';
          return '';
        }
      }
    }
  }
}

如果你提前固定了Y轴的最大最小值,也可以直接写死两个刻度的数值,不需要动态计算,运行稳定性更高。

内容的提问来源于stack exchange,提问作者aljabadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:24:04