如何用Vega-Lite优雅实现月度循环叠加时间序列图?
用Vega-Lite实现月度循环对比折线图
核心思路是通过数据转换标记系列类别+分层图层叠加聚合数据来实现,以下是可直接复用的配置方案:
步骤1:数据预处理与系列标记
先提取时间维度的年、月信息,自动识别最新年份,标记出「当前年度」「上一年度」的数据;同时单独筛选过去五年的数据并按月份求平均:
{ "data": {"values": [{"t":"2020-01-31", "price": 90}, {"t":"2020-02-28", "price": 92}, ...]}, // 替换为你的原始数据 "transform": [ // 提取年、月维度 {"timeUnit": "year", "field": "t", "as": "year"}, {"timeUnit": "month", "field": "t", "as": "month"}, // 计算最新年份并同步到每一行数据 {"joinaggregate": [{"op": "max", "field": "year", "as": "latest_year"}]}, // 标记当前年、上年的系列类别 {"calculate": "case( datum.year === datum.latest_year, '当前年度', datum.year === datum.latest_year - 1, '上一年度', null )", "as": "series"}, // 过滤非目标年份数据(保留当前年、上年用于折线绘制) {"filter": "datum.series !== null"} ], // 后续配置见分层图层部分 }
步骤2:分层叠加五年平均折线
用layer图层将「当前/上年原始数据折线」和「过去五年平均折线」叠加,后者需单独做聚合转换:
{ "layer": [ // 图层1:当前年度、上一年度折线 { "mark": {"type": "line", "point": true}, "encoding": { "x": { "field": "month", "type": "temporal", "timeUnit": "month", "axis": { "format": "%B", // 显示完整月份名,用%b可显示缩写 "labelAngle": 0, "tickCount": 12 // 强制显示12个月份刻度 }, "title": "月份" }, "y": {"field": "price", "type": "quantitative", "title": "价格"}, "color": {"field": "series", "type": "nominal", "title": "数据系列"}, "strokeDash": {"field": "series", "type": "nominal"} // 用虚线区分不同系列 } }, // 图层2:过去五年平均折线 { "data": {"values": [{"t":"2020-01-31", "price": 90}, ...]}, // 复用你的原始数据 "transform": [ {"timeUnit": "year", "field": "t", "as": "year"}, {"timeUnit": "month", "field": "t", "as": "month"}, {"joinaggregate": [{"op": "max", "field": "year", "as": "latest_year"}]}, // 筛选过去五年的数据(含当前年) {"filter": "datum.year >= datum.latest_year - 4"}, // 按月份聚合求平均 {"aggregate": [{"op": "mean", "field": "price", "as": "avg_price"}], "groupby": ["month"]}, // 标记系列类别 {"calculate": "'过去五年平均'", "as": "series"} ], "mark": {"type": "line", "point": true, "color": "#888", "strokeWidth": 2}, "encoding": { "x": {"field": "month", "type": "temporal", "timeUnit": "month"}, "y": {"field": "avg_price", "type": "quantitative"} } } ], "resolve": {"scale": {"y": "shared"}}, // 确保两个图层共用Y轴刻度 "title": "年度价格月度对比" }
关键细节说明
- 固定12个月坐标轴:通过
x.axis.tickCount: 12强制生成12个月份刻度,结合timeUnit: month保证轴显示完整的月度循环。 - 系列区分:用颜色+虚线样式区分三类数据,五年平均用灰色粗线突出参考性。
- 自动适配最新年份:通过
joinaggregate获取最新年份,无需硬编码年份值,配置可自动适配后续新增数据。
内容的提问来源于stack exchange,提问作者Arie
相关产品推荐
相关产品推荐

