Search code examples
vegavega-lite

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


How do I use the value of a slider in the transform?

This example from vega online editor plots a sine and cosine wave.

{
  "$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
    }
  }
}

I would like to add two sliders and use their values in the calculation. I can define sliders using:

  "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}
      }
    }
  },

How do I access the slider values to use in the calculations? Something like

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

Solution

  • You can do this in exactly the way you wrote in your question. Additionally, adding an initial value will make the selections valid before you interact with them.

    Here is a full example (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}
          }
        }
      }
    }