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

Vega-Lite条件轴优化:实现年份在首个有效刻度显示

解决Vega-Lite轴刻度首个位置显示年份的方案

核心思路是通过刻度的索引判断是否为第一个有效刻度,仅在该位置显示年份+月份的两行标签,其余位置只显示月份,完美适配包含任意起始月份的图表场景。

以下是完整的配置示例:

{
  "data": {"url": "data/seattle-weather.csv"},
  "mark": "line",
  "encoding": {
    "x": {
      "field": "date",
      "type": "temporal",
      "axis": {
        "labelExpr": "datum.index === 0 ? (timeFormat(datum.value, '%b') + '\\n' + timeFormat(datum.value, '%Y')) : timeFormat(datum.value, '%b')",
        "labelAngle": 0,
        "labelAlign": "center"
      },
      "timeUnit": "month"
    },
    "y": {"field": "precipitation", "type": "quantitative"}
  }
}

关键逻辑说明

  • datum.index === 0:判断当前刻度是否为图表的第一个有效刻度,无论该刻度对应的月份是1月还是其他月份
  • timeFormat(datum.value, '%b') + '\\n' + timeFormat(datum.value, '%Y'):在第一个刻度位置,通过\n换行实现月份(缩写)和年份的两行显示
  • 其余刻度仅渲染月份缩写,保持标签简洁

内容的提问来源于stack exchange,提问作者Susmit Kumar Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:43:12