Stack#

The stack transform allows you to compute values associated with stacked versions of encodings. For example, consider this stacked bar chart:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    column='year:O',
    x='yield:Q',
    y='variety:N',
    color='site:N'
).properties(width=220)

Implicitly, this data is being grouped and stacked, but what if you would like to access those stacked values directly? We can construct that same chart manually using the stack transform:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).transform_stack(
    stack='yield',
    as_=['yield_1', 'yield_2'],
    groupby=['year', 'variety'],
    sort=[alt.SortField('site', 'descending')]
).mark_bar().encode(
    column='year:O',
    x=alt.X('yield_1:Q').title('yield'),
    x2='yield_2:Q',
    y='variety:N',
    color='site:N',
    tooltip=['site', 'yield', 'variety']
).properties(width=220)

Notice that the bars are now explicitly drawn between values computed and specified within the x and x2 encodings.

Transform Options#

The transform_stack() method is built on the StackTransform class, which has the following options:

Click to show table

Property

Type

Description

as

anyOf(FieldName, array(FieldName))

Output field names. This can be either a string or an array of strings with two elements denoting the name for the fields for stack start and stack end respectively. If a single string(e.g., "val") is provided, the end field will be "val_end".

groupby

array(FieldName)

The data fields to group by.

offset

[‘zero’, ‘center’, ‘normalize’]

Mode for stacking marks. One of "zero" (default), "center", or "normalize". The "zero" offset will stack starting at 0. The "center" offset will center the stacks. The "normalize" offset will compute percentage values for each stack point, with output values in the range [0,1].

Default value: "zero"

sort

array(SortField)

Field that determines the order of leaves in the stacked charts.

stack

FieldName

The field which is stacked.