问题
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)
回答1:
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
)
Unfortunately, Vega-Lite does not currently provide any native way to create a slider that displays a formatted date.
来源:https://stackoverflow.com/questions/62046930/altair-adding-date-slider-for-interactive-scatter-chart-pot