如何在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" }
关键修改说明:
- 转换时间戳:原始
date是字符串类型的毫秒数,先用toNumber转成数值,再用toDate转换成Vega-Lite能识别的日期对象,存为新字段formatted_date。 - 指定时间类型:X轴字段类型设为
temporal,告诉Vega-Lite这是时间数据,自动按时间轴逻辑处理。 - 配置轴显示格式:通过
axis.format设置日期显示样式,遵循D3时间格式语法,常用选项:%d:两位日期(01-31)%b:月份英文缩写(Jan/Feb/...)%m:两位数字月份(01-12)%Y:四位年份(2011)
内容的提问来源于stack exchange,提问作者Emi
相关产品推荐
相关产品推荐

