Altair: use a field to specify the domain of the Y axis?

Viewed 1606

Is it possible to use a field in the data to specify the domain of the Y axis?

I've tried something like this but it is not working:

scale=alt.Scale(domain = ['field1','field2'])

Suppose I have an interactive plot like the below, and I want the Y axis domain to change with the selection in the legend.

import altair as alt
from vega_datasets import data

source = data.unemployment_across_industries.url
source = pd.read_json(source)
source['field1'] = 0
source['field2'] = 20000

selection = alt.selection_multi(fields=['series'], bind='legend')

alt.Chart(source).mark_area().encode(
    alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
    alt.Y('sum(count):Q', stack='center', scale=alt.Scale(domain = ['field1','field2'])),
    alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
    opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).add_selection(
    selection
)
1 Answers

No, the domain can only be set to a pair of numbers. If you want the domain to respond to the selection, one way to do so is to use a filter transform without an explicit domain. For example:

source = data.unemployment_across_industries.url

selection = alt.selection_multi(fields=['series'], bind='legend')

alt.Chart(source).mark_area().encode(
    alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
    alt.Y('sum(count):Q', stack='center'),
    alt.Color('series:N', scale=alt.Scale(scheme='category20b'))
).add_selection(
    selection
).transform_filter(selection)
Related