Calculate Transform

The calculate transform allows the user to define new fields in the dataset which are calculated from other fields using an expression syntax.

As a simple example, here we take data with a simple input sequence, and compute a some trigonometric quantities:

import altair as alt
import pandas as pd

data = pd.DataFrame({'t': range(101)})

alt.Chart(data).mark_line().encode(
    x='x:Q',
    y='y:Q',
    order='t:Q'
).transform_calculate(
    x='cos(datum.t * PI / 50)',
    y='sin(datum.t * PI / 25)'
)

Each argument within transform_calculate is a Vega expression string, which is a well-defined set of javascript-style operations that can be used to calculate a new field from an existing one.

To streamline building these vega expressions in Python, Altair provides the altair.expr module which provides constants and functions to allow these expressions to be constructed with Python syntax; for example:

from altair import expr, datum

alt.Chart(data).mark_line().encode(
    x='x:Q',
    y='y:Q',
    order='t:Q'
).transform_calculate(
    x=expr.cos(datum.t * expr.PI / 50),
    y=expr.sin(datum.t * expr.PI / 25)
)

Altair expressions are designed to output valid Vega expressions. The benefit of using them is that proper syntax is ensured by the Python interpreter, and tab completion of the expr submodule can be used to explore the available functions and constants.

These expressions can also be used when constructing a Filter Transform, as we shall see next.

Transform Options

The transform_calculate() method is built on the CalculateTransform class, which has the following options:

Property Type Description
as FieldName The field for storing the computed formula value.
calculate string A expression string. Use the variable datum to refer to the current data object.