Vega-Lite:如何在变换计算中使用滑块值

Vega-Lite: How to use slider value in transform calculation

如何在变换中使用滑块的值?

这个来自 vega 在线编辑器的 example 绘制了一个正弦波和余弦波。

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Plots two functions using a generated sequence.",
  "width": 300,
  "height": 150,
  "data": {
    "sequence": {
      "start": 0,
      "stop": 12.7,
      "step": 0.1,
      "as": "x"
    }
  },
  "transform": [
    {
      "calculate": "sin(datum.x)",
      "as": "sin(x)"
    },
    {
      "calculate": "cos(datum.x)",
      "as": "cos(x)"
    },
    {
      "fold": ["sin(x)", "cos(x)"]
    }
  ],
  "mark": "line",
  "encoding": {
    "x": {
      "type": "quantitative",
      "field": "x"
    },
    "y": {
      "field": "value",
      "type": "quantitative"
    },
    "color": {
      "field": "key",
      "type": "nominal",
      "title": null
    }
  }
}

我想添加两个滑块并在计算中使用它们的值。我可以使用以下方式定义滑块:

  "selection" : {
    "amp" : {
      "type" : "single",
      "fields" : ["sin", "cos"],
      "bind": {
        "sin": { "input" : "range", "min": 0.0, "max": 10.0, "step": 0.1},
        "cos": { "input" : "range", "min": 0.0, "max": 10.0, "step": 0.1}
      }
    }
  },

如何访问要在计算中使用的滑块值?像

    {
      "calculate": "amp.sin * sin(datum.x)",
      "as": "sin(x)"
    },

您可以完全按照您在问题中所写的方式进行操作。此外,添加初始值将使选择在您与它们交互之前有效。

这是一个完整的示例 (vega editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Plots two functions using a generated sequence.",
  "width": 300,
  "height": 150,
  "data": {"sequence": {"start": 0, "stop": 12.7, "step": 0.1, "as": "x"}},
  "transform": [
    {"calculate": "amp.sin * sin(datum.x)", "as": "sin(x)"},
    {"calculate": "amp.cos * cos(datum.x)", "as": "cos(x)"},
    {"fold": ["sin(x)", "cos(x)"]}
  ],
  "mark": "line",
  "encoding": {
    "x": {"type": "quantitative", "field": "x"},
    "y": {"field": "value", "type": "quantitative"},
    "color": {"field": "key", "type": "nominal", "title": null}
  },
  "selection": {
    "amp": {
      "type": "single",
      "fields": ["sin", "cos"],
      "init": {"sin": 1, "cos": 1},
      "bind": {
        "sin": {"input": "range", "min": 0, "max": 10, "step": 0.1},
        "cos": {"input": "range", "min": 0, "max": 10, "step": 0.1}
      }
    }
  }
}