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

如何修改ChartJS图表X轴日期显示格式,实现月日分行展示效果?

ChartJS X轴日期标签分行显示解决方案

最简实现方案

ChartJS原生支持数组格式的轴标签,数组中每一个元素会自动渲染为独立的一行,无需额外引入依赖或配置复杂样式,你只需要调整labels的生成逻辑即可:

  • 把原来返回拼接后月日字符串的逻辑,修改为返回包含月份、日期两个元素的数组
  • 若需要调整两行文字的间距,可以在x轴配置中添加ticks.lineHeight参数控制行高

修改后的完整代码如下:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        // 拆分月日为数组,自动分行显示
        labels: data.map(x => [moment(x.date).format("MMM"), moment(x.date).format("Do")]),
        datasets: [{
            data: data.map(x => x.premium),
            backgroundColor: '#ffec87',
            borderColor: "#ffec87",
            borderWidth: 2,
            borderStyle: 'dotted'
        }]
    },
  options: {
    scales: {
      xAxis: { 
        grid: { display: false },
        // 可选:调整标签行间距
        ticks: { lineHeight: 1.4 }
      },
      yAxis: { grid: { borderDash: [3, 5] } }
    }
  }
});

进阶优化方案(同月份仅显示一次月份)

如果希望避免同一个月的日期重复显示月份,减少标签冗余,可以通过x轴刻度的回调函数实现:

options: {
  scales: {
    xAxis: { 
      grid: { display: false },
      ticks: {
        lineHeight: 1.4,
        callback: function(value, index, ticks) {
          const currentDate = data[index].date;
          const currentMonth = moment(currentDate).format("MMM");
          const currentDay = moment(currentDate).format("Do");
          // 首条标签直接显示月+日
          if (index === 0) {
            return [currentMonth, currentDay];
          }
          // 和上一个日期对比月份,相同则只显示日
          const prevMonth = moment(data[index-1].date).format("MMM");
          return currentMonth === prevMonth ? currentDay : [currentMonth, currentDay];
        }
      }
    },
    yAxis: { grid: { borderDash: [3, 5] } }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:39:03