altair

Setting the default Altair selection interval domain


I can setup an Altair chart with a secondary chart as the selection interval. What I need to be able to do is set the initially displayed interval to be less than the full scale.

The example I'm working from is below:

import altair as alt
from vega_datasets import data

weather = data.seattle_weather()
weather.head()

interval = alt.selection_interval(encodings=['x'])


base = alt.Chart(weather).mark_rule(size=2).encode(
    x='date:T',
    y='temp_min:Q',
    y2='temp_max:Q',
    color='weather:N'
)

chart = base.encode(
    x=alt.X('date:T', scale=alt.Scale(domain=interval.ref()))
).properties(
    width=800,
    height=300
)

view = base.add_selection(
    interval
).properties(
    width=800,
    height=50,
)

chart & view

I assume I need to add some other parameters into encodings of interval = alt.selection_interval(encodings=['x']), but I'm too new to Altair to understand where to go from here.


Solution

  • I can't try your code because I don't know what the weather data looks like, but if I understand you correctly, your issue could be solved by setting the value (init in altair <5) parameter of the selection interval:

    import altair as alt
    from vega_datasets import data
    
    source = data.cars()
    brush = alt.selection_interval(value={'y': [20, 40]})
    
    alt.Chart(source).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
        color=alt.condition(brush, 'Cylinders:O', alt.value('grey')),
    ).add_params(brush)
    

    enter image description here

    More info in the docs https://altair-viz.github.io/user_guide/interactions.html#encoding-channel-binding