Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altair adding date slider for interactive scatter chart pot

Has anyone tried using date as a slider for Altair interactive scatter plots?

I'm trying to reproduce a similar plot to the gapminder scatter: 1) Instead of a year filter I'm trying to use a date e.g. '2020-01-05' and having the follow error:

    altair.vegalite.v4.schema.core.BindRange->max, validating 'type'

    '2020-05-17T00:00:00' is not of type 'number'

2) When I try to parse it as an int, nothing shows up in the plot 3) Examples of using the Year slider: https://www.datacamp.com/community/tutorials/altair-in-python https://altair-viz.github.io/gallery/multiple_interactions.html 4) Also a timestamp option wouldn't be ideal as the date needs to be readable Would appreciate any help. Thanks

#Date Slider
from altair import datum
from datetime import datetime
import altair as alt
import pandas as pd
import numpy as np
import datetime as dt

date_slider = alt.binding_range(min=min(df['date']), max=max(df['date']), step=1)
slider_selection = alt.selection_single(bind=date_slider, fields=['date'], name="Date", init={'week_starting': max(df[‘date’]})

alt.Chart(df).mark_point(filled=True).encode(
    x='mom_pct',
    y='yoy_pct',
    size='n_queries',
    color='vertical',
    tooltip = ['vertical', 'yoy_pct', 'mom_pct']
).properties(
    width=800,
    height=600
).add_selection(slider_selection).transform_filter(slider_selection)
like image 768
Rob Avatar asked Oct 21 '25 04:10

Rob


2 Answers

Another way to workaround this issue is using another chart in place of the slider. This let's your see the date as well as using a range for the selection which is also not possible with sliders at the moment.

import altair as alt
from vega_datasets import data
import pandas as pd


# Convert date column to an actual date and filter the data.
movies = (
    data.movies()
    .assign(Release_Date=lambda df: pd.to_datetime(df['Release_Date']))
    .query('1960 < Release_Date < 2010')
    .sample(1_000, random_state=90384))

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

bar_slider = alt.Chart(movies).mark_bar().encode(
    x='year(Release_Date)',
    y='count()').properties(height=50).add_selection(select_year)

scatter_plot = alt.Chart(movies).mark_circle().encode(
    x='Rotten_Tomatoes_Rating',
    y='IMDB_Rating',
    opacity=alt.condition(
        select_year,
        alt.value(0.7), alt.value(0.1)))

scatter_plot & bar_slider

enter image description here

like image 155
joelostblom Avatar answered Oct 24 '25 16:10

joelostblom


Vega-Lite sliders do not support datetime display, but it is possible to display timestamps. Here is a full example (I didn't base it off of your code, because you did not provide any data):

import altair as alt
import pandas as pd
import numpy as np
from datetime import datetime

datelist = pd.date_range(datetime.today(), periods=100).tolist()

rand = np.random.RandomState(42)

df = pd.DataFrame({
    'xval': datelist,
    'yval': rand.randn(100).cumsum(),
})

def timestamp(t):
  return pd.to_datetime(t).timestamp() * 1000

slider = alt.binding_range(name='cutoff:', min=timestamp(min(datelist)), max=timestamp(max(datelist)))
selector = alt.selection_single(name="SelectorName", fields=['cutoff'],
                            bind=slider,init={"cutoff": timestamp("2020-05-05")})

alt.Chart(df).mark_point().encode(
    x='xval',
    y='yval',
    opacity=alt.condition(
        'toDate(datum.xval) < SelectorName.cutoff[0]',
        alt.value(1), alt.value(0)
    )
).add_selection(
    selector
)

enter image description here

Unfortunately, Vega-Lite does not currently provide any native way to create a slider that displays a formatted date.

like image 20
jakevdp Avatar answered Oct 24 '25 18:10

jakevdp