如何在Vega Lite中使用“乘”或“自定义fn”聚合?

时间:2020-01-14 18:14:50

标签: vega-lite

在下面的示例中,使用了mean聚合。如何将聚合计算为所有元素的乘积?

并且可以使用自定义JS函数吗?像const myfn = (list) => list.length一样,(我知道有一个count插件,只是为了说明这个想法)。

Playground

{
  "data": {"url": "data/cars.json"},
  "mark": "bar",
  "encoding": {
    "x": {"field": "Cylinders", "type": "ordinal"},
    "y": {"aggregate": "mean", "field": "Acceleration", "type": "quantitative"}
  }
}

1 个答案:

答案 0 :(得分:1)

不幸的是,产品不是Vega-Lite中的Built-in Aggregations之一,并且根据设计,该架构不支持注入任意Javascript函数(它支持有限的Vega Expression语法)。除非您在将数据注入Vega-Lite规范之前对其进行预处理,否则您将只能从那里可用的操作中构建自定义计算。

对于您的特定问题,由于产品的对数等于对数的总和,因此可以在规范内计算产品的一种方法是通过一系列如下所示的变换(playground):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {"url": "data/cars.json"},
  "transform": [
    {"calculate": "log(datum.Acceleration)", "as": "logA"},
    {"aggregate": [{"op": "sum", "field": "logA", "as": "log_prod_A"}], "groupby": ["Cylinders"]},
    {"calculate": "exp(datum.log_prod_A)", "as": "prod_A"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "Cylinders", "type": "ordinal"},
    "y": {"field": "prod_A", "type": "quantitative", "title": "prod(A)"}
  }
}

enter image description here

单个条形占主导地位,因为使用4缸的条目比使用其他数字的条目要多。