Vega Lite
Data Transformation
Calculate

How Can I Use the Calculate Transform in Vega-Lite?

Do you ever find yourself needing to create a new field in your data for better visualizations? Vega-Lite offers a powerful solution with the Calculate Transform. This guide will help you understand how to use it effectively.

What is the Calculate Transform?

The Calculate Transform allows you to extend your dataset with new fields (columns) based on expressions. This means you can create additional variables derived from existing ones, which can then be utilized in your visualizations.

Here is a general template for how to use it:

// Any View Specification
{
  ...
  "transform": [
    {"calculate": "expression", "as": "newFieldName"} // Calculate Transform
    ...
  ],
  ...
}

How to Define a Calculate Transform

The Calculate Transform can be defined using the properties calculate and as.

PropertyTypeDescription
calculateStringRequired. A expression string. Use the variable datum to refer to the current data object.
asStringRequired. The field for storing the computed formula value.

A Use Case

In this example, we use a calculate transform that doubles the b field in the data source, and it derives a new field b2.

{
  "data": {
    "values": [
      {"a": "A", "b": 28},
      {"a": "B", "b": 55},
      {"a": "C", "b": 43},
      {"a": "G", "b": 19},
      {"a": "H", "b": 87},
      {"a": "I", "b": 52},
      {"a": "D", "b": 91},
      {"a": "E", "b": 81},
      {"a": "F", "b": 53}
    ]
  },
  "transform": [
    {"calculate": "2*datum.b", "as": "b2"},
  ],
  "mark": "bar",
  "encoding": {
    "y": {"field": "b2", "type": "quantitative"},
    "x": {"field": "a", "type": "ordinal"}
  }
}