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

Chart.js 标注插件:能否为同名X轴标签添加多条垂直线?

解决Chart.js中重复X轴标签的垂直线定位问题

这个问题我之前也碰到过!用字符串作为X轴标签的话,Chart.js确实没法区分重复的12:00am,因为它只会匹配第一个出现的标签。不过有两种靠谱的解决办法,完全不用修改你最终显示的X轴标签:


方法一:用时间刻度(推荐,更灵活)

核心思路是让X轴的底层数据是唯一的时间值(日期对象/时间戳),只是把显示格式改成小时,这样每个12:00am都是不同的时间点,就能精准定位了。

具体步骤:

  1. 更新数据源:把原来的X轴字符串标签换成完整的日期对象。比如假设你的数据是过去三天(5.20-5.22),每个数据点的X值应该是new Date('2024-05-20T00:00:00')、new Date('2024-05-20T01:00:00')...直到new Date('2024-05-22T23:00:00')。
  2. 引入时间适配器:Chart.js的时间刻度需要依赖第三方适配器,比如chartjs-adapter-date-fns(需同时引入date-fns)或者chartjs-adapter-moment。
  3. 配置X轴:把X轴的type设为time,并设置显示格式为小时:
scales: {
  x: {
    type: 'time',
    time: {
      unit: 'hour',
      displayFormats: {
        hour: 'h:mma' // 显示成12:00am、1:00pm这种格式
      }
    }
  }
}
  1. 配置标注:每个垂直线对应一个具体的0点日期对象:
annotation: {
  annotations: [
    {
      type: 'line',
      id: 'vLine1',
      mode: 'vertical',
      display: true,
      scaleID: 'x',
      value: new Date('2024-05-20T00:00:00'), // 第一天的0点
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 1' }
    },
    {
      type: 'line',
      id: 'vLine2',
      mode: 'vertical',
      display: true,
      scaleID: 'x',
      value: new Date('2024-05-21T00:00:00'), // 第二天的0点
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 2' }
    },
    {
      type: 'line',
      id: 'vLine3',
      mode: 'vertical',
      display: true,
      scaleID: 'x',
      value: new Date('2024-05-22T00:00:00'), // 第三天的0点
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 3' }
    }
  ]
}

方法二:用索引定位(适合固定24小时/天的场景)

如果你的数据是严格每天24小时,没有缺失或多余的点,可以直接用X轴的索引来定位:

  • 第一天的12:00am是索引0
  • 第二天的12:00am是索引24
  • 第三天的12:00am是索引48

然后把标注的value换成对应的索引即可:

annotation: {
  annotations: [
    {
      type: 'line',
      id: 'vLine1',
      mode: 'vertical',
      display: true,
      scaleID: 'x-axis-0',
      value: 0, // 第一天0点的索引
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 1' }
    },
    {
      type: 'line',
      id: 'vLine2',
      mode: 'vertical',
      display: true,
      scaleID: 'x-axis-0',
      value: 24, // 第二天0点的索引
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 2' }
    },
    {
      type: 'line',
      id: 'vLine3',
      mode: 'vertical',
      display: true,
      scaleID: 'x-axis-0',
      value: 48, // 第三天0点的索引
      borderWidth: 1,
      borderColor: 'gray',
      label: { enabled: true, position: 'center', content: 'Day 3' }
    }
  ]
}

小提示

第一种方法更推荐,因为如果后续数据有变化(比如某天少了几个小时),索引定位就会出错,而时间刻度会自动适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:07:39