【问题标题】:vega-lite: how to aggregate by weekvega-lite:如何按周聚合
【发布时间】:2020-04-17 07:31:54
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: vega-lite


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2018-03-12
    • 2020-02-01
    • 2020-03-19
    • 2017-03-26
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多