您可以使用步长为 7 的 monthdate timeUnit 按周分组:
"timeUnit": {"unit": "monthdate", "step": 7}
例如:
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"url": "data/seattle-temps.csv"},
"mark": "line",
"encoding": {
"x": {"timeUnit": {"unit": "yearmonthdate", "step": 7}, "field": "date", "type": "temporal"},
"y": {"aggregate": "mean", "field": "temp", "type": "quantitative"}
}
}
不过请注意,这会在每个月初开始新的一周,这意味着如果您按星期几和星期几做热图,就会有间隔:
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"url": "data/seattle-temps.csv"},
"mark": "rect",
"encoding": {
"y": {"timeUnit": "day", "field": "date", "type": "ordinal"},
"x": {"timeUnit": {"unit": "yearmonthdate", "step": 7}, "field": "date", "type": "ordinal"},
"color": {"aggregate": "mean", "field": "temp", "type": "quantitative"}
}
}
如果您想要更细粒度地控制周的开始位置,很遗憾,这不能表示为 timeUnit,但您可以利用 Vega-Lite 的完整 transform 语法来制作更多自定义聚合。例如,这里我们通过计算数据中的星期日来计算一年中的一周:
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"url": "data/seattle-temps.csv"},
"transform": [
{"timeUnit": "yearmonthdate", "field": "date", "as": "date"},
{
"aggregate": [{"op": "mean", "field": "temp", "as": "temp"}],
"groupby": ["date"]
},
{"calculate": "day(datum.date) == 0", "as": "sundays"},
{
"window": [{"op": "sum", "field": "sundays", "as": "week"}],
"sort": "date"
}
],
"mark": "rect",
"encoding": {
"y": {"timeUnit": "day", "field": "date", "type": "ordinal", "title": "Day of Week"},
"x": {"field": "week", "type": "ordinal", "title": "Week of year"},
"color": {"aggregate": "mean", "field": "temp", "type": "quantitative"}
}
}