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

如何在Vega-Lite中从时间戳提取日和月显示在X轴?

解决Vega-Lite X轴时间戳转日/月格式的问题

直接修改配置,通过转换字段类型+配置轴格式就能实现,完整代码如下:

{
  "data": {
    "values": [
      {"date": "1325376000000", "price": 0},
      {"date": "1325462400000", "price": 100},
      {"date": "1325548800000", "price": 30}
    ]
  },
  "transform": [
    // 把字符串类型的毫秒时间戳转成日期对象
    {"calculate": "toDate(toNumber(datum.date))", "as": "formatted_date"}
  ],
  "mark": "line",
  "encoding": {
    "x": {
      "field": "formatted_date",
      "type": "temporal", // 指定为时间类型
      "axis": {
        "format": "%d-%b" // 日-月份缩写格式,比如"01-Jan"
        // 可选格式:"%d/%m" → 01/01,"%d %b" → 01 Jan
      }
    },
    "y": {"field": "price", "type": "quantitative"}
  },
  "width": "container"
}

关键修改说明:

  1. 转换时间戳:原始date是字符串类型的毫秒数,先用toNumber转成数值,再用toDate转换成Vega-Lite能识别的日期对象,存为新字段formatted_date。
  2. 指定时间类型:X轴字段类型设为temporal,告诉Vega-Lite这是时间数据,自动按时间轴逻辑处理。
  3. 配置轴显示格式:通过axis.format设置日期显示样式,遵循D3时间格式语法,常用选项:
    • %d:两位日期(01-31)
    • %b:月份英文缩写(Jan/Feb/...)
    • %m:两位数字月份(01-12)
    • %Y:四位年份(2011)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:45:32