vega-lite:如何按周汇总

vega-lite: how to aggregate by week

我看到可以使用多个时间单位进行聚合,例如按月,而不是按周。

而且我看到在 vega 中可以自定义时间单位 https://vega.github.io/vega/docs/transforms/timeunit/#chronological-time-units

是否可以在 vega-lite 中使用它并按周聚合,并在示例 this aggregation 中从月到周进行转换?

谢谢

您可以使用步长为 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"}
  }
}