Search code examples
pythonaltair

How to have init values for a selection interval in Altair when using dates?


I'm trying to have initial values for a selection_interval in a Altair plot, but I've been unable to figure it out.

Here is a code snippet:

df = pd.DataFrame({'date': {0: '2005-03-01', 1: '2005-04-01', 2: '2005-05-02'}, 
                   'values': {0: 89.2506, 1: 109.4073, 2: 120.8222}})

interval = alt.selection_interval(encodings=['x'],init = {'x':['2005-03-01', '2005-04-01']})

alt.Chart(df).mark_line().encode(x =  alt.X('date:T'), y = alt.Y('values')).add_selection(interval)

I expected the area between '2005-03-01' and '2005-04-01' to be highlighted when the plot initializes.

Thanks in advance for the help!


Solution

  • Solution for Altair version < 5.x

    It appears that Vega-Lite is not recognizing and converting timestamps within the init argument. You can get around this by using Pandas to convert the dates to timestamps manually:

    x_init = pd.to_datetime(['2005-03-01', '2005-04-01']).astype(int) / 1E6
    interval = alt.selection_interval(encodings=['x'], init={'x':list(x_init)})
    

    Solution for Altair version >= 5.x

    x_init = pd.to_datetime(['2005-03-01', '2005-04-01']).astype(int) / 1E6
    interval = alt.selection_interval(encodings=['x'], value={'x':list(x_init)})