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

如何在react-chart-js2折线图中仅显示每第三个小时标签?

实现仅显示每第三个小时标签的方案

完全可以实现,给你两种可行的方案:

方案一:直接过滤标签数组

在生成labels的时候,通过索引判断只保留每第三个标签,其余位置留空字符串(Chart.js会自动隐藏空标签):

const data = {
  labels: chart.prices?.map((x, index) => 
    index % 3 === 0 ? moment(x[0]).format('h:mm a') : ''
  ),
  datasets: [{
    data: chart.prices?.map(x => x[1]),
    backgroundColor: '#ffffff00',
    borderColor: 'rgb(79 70 229)',
    borderWidth: '2',
    pointBorderColor: '#ffffff00',
    tension: 0.4,
    fill: {
      target: "origin",
      above: "rgba(79, 70, 229, 0.0625)"
    }
  }]
}

方案二:通过Chart.js配置控制显示

保持labels数组完整,在图表的options里配置X轴的ticks.callback函数,只返回每第三个标签:

const data = {
  labels: chart.prices?.map(x => moment(x[0]).format('h:mm a')),
  datasets: [{
    data: chart.prices?.map(x => x[1]),
    backgroundColor: '#ffffff00',
    borderColor: 'rgb(79 70 229)',
    borderWidth: '2',
    pointBorderColor: '#ffffff00',
    tension: 0.4,
    fill: {
      target: "origin",
      above: "rgba(79, 70, 229, 0.0625)"
    }
  }]
}

const options = {
  scales: {
    x: {
      ticks: {
        callback: function(value, index) {
          // 仅显示索引为3的倍数的标签
          return index % 3 === 0 ? this.getLabelForValue(value) : '';
        }
      }
    }
  }
}

// 渲染图表时传入options
<Line data={data} options={options} />

两种方案的区别:

  • 方案一直接修改了数据源的标签数组,适合不需要保留完整标签数据的场景
  • 方案二保留了完整的标签数据,只是通过配置控制显示,更灵活,后续如果需要调整显示规则只改配置就行

内容的提问来源于stack exchange,提问作者Jakub Polański

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:36:12