Vega Plugins#

Plugins extend Vega with custom functions, transforms, and other chart features. Use one when your specification needs an extension that Vega does not include. The Vega extensibility API lists the registration functions a plugin can call.

Warning

A plugin is executable JavaScript. Load plugin files and URLs only from sources you trust. Do not accept caller-supplied plugins on a public service unless you have decided to accept that risk

Create a Plugin#

A plugin is a JavaScript ECMAScript module (ESM) whose default export is a function. VlConvert calls that function with the Vega module when a worker starts, before any specification is compiled or parsed.

Save this example as double-value.js:

double-value.js
export default function registerDoubleValue(vega) {
  vega.expressionFunction("doubleValue", value => value * 2)
}

Save this Vega-Lite specification:

chart.vl.json
{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "data": {
    "values": [
      {"category": "A", "value": 2},
      {"category": "B", "value": 5}
    ]
  },
  "transform": [
    {"calculate": "doubleValue(datum.value)", "as": "doubled"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "category", "type": "nominal"},
    "y": {"field": "doubled", "type": "quantitative"}
  }
}

The calculate transform can now call doubleValue.

Register the Plugin#

Register the plugin when starting the server:

$ vl-convert serve \
>   --vega-plugin ./double-value.js \
>   --port 3000

Every request handled by this process can then use doubleValue. Put the specification above in the spec field of a normal /vegalite/* request. Save this complete request body as request.json:

request.json
{
  "spec": {
    "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
    "data": {
      "values": [
        {
          "category": "A",
          "value": 2
        },
        {
          "category": "B",
          "value": 5
        }
      ]
    },
    "transform": [
      {
        "calculate": "doubleValue(datum.value)",
        "as": "doubled"
      }
    ],
    "mark": "bar",
    "encoding": {
      "x": {
        "field": "category",
        "type": "nominal"
      },
      "y": {
        "field": "doubled",
        "type": "quantitative"
      }
    }
  }
}
$ curl http://127.0.0.1:3000/vegalite/png \
>   -H 'Content-Type: application/json' \
>   --data-binary @request.json \
>   --output chart.png

The registered doubleValue function doubles the source values before Vega draws these bars:

Two bars with the source values doubled to four and ten

Plugins can also come from HTTPS URLs or inline source, and a plugin can import other modules. See Plugin Loading and Security for loading modes, import allowlists, prebundling, and caller-supplied plugins, and Security and Network Access for the wider trust model.