如何在 vega 公式变换中使用阶乘 (!)

问题描述

我正在尝试使用 vega js 规范创建 binomial distribution PMF 的直方图。

这通常是怎么做的? vega expressions包括 choosefactorial函数,也不包括 statistical functions 下的二项式分布。

我似乎也无法引用 vega 规范中的其他函数(即下面的 yval)。

  "data":[
{"name": "dataset","transform": [
  {"type":"sequence","start": 1,"stop": 50,"step": 1,"as": "seq" },{"type": "formula","as": "xval","expr": "if(datum.seq<nval,datum.seq,NaN)"},"as": "yval","expr": "math.factorial(datum.xval)
  " }
]}],

谢谢。

解决方法

没有可用的阶乘运算,但一种合适的选择可能是使用 Stirling's approximation 对其进行近似处理,或者如果需要更高的准确性,也可以使用 Stirling series

例如,在 Vega-Lite (view in editor) 中:

{
  "data": {
    "values": [
      {"n": 0,"factorial": 1},{"n": 1,{"n": 2,"factorial": 2},{"n": 3,"factorial": 6},{"n": 4,"factorial": 24},{"n": 5,"factorial": 120},{"n": 6,"factorial": 720},{"n": 7,"factorial": 5040},{"n": 8,"factorial": 40320},{"n": 9,"factorial": 362880},{"n": 10,"factorial": 3628800}
    ]
  },"transform": [
    {
      "calculate": "datum.n == 0 ? 1 : sqrt(2 * PI * datum.n) * pow(datum.n / E,datum.n)","as": "stirling"
    },{"fold": ["factorial","stirling"]}
  ],"mark": "point","encoding": {
    "x": {"field": "n","type": "quantitative"},"y": {"field": "value","type": "quantitative","scale": {"type": "log"}},"color": {"field": "key","type": "nominal"}
  }
}

enter image description here