Altair交互式散点图锅添加日期滑块 [英] Altair adding date slider for interactive scatter chart pot
问题描述
有人尝试过使用日期作为Altair交互式散点图的滑块吗?
我正试图重现与gapminder散布相似的情节:1)我尝试使用日期而不是年份过滤器'2020-01-05',并出现以下错误:
altair.vegalite.v4.schema.core.BindRange-> max,验证类型"'2020-05-17T00:00:00'不是'number'类型的
2)当我尝试将其解析为int时,图中未显示任何内容3)使用年"滑块的示例:
不幸的是,Vega-Lite当前不提供任何本机方式来创建显示格式化日期的滑块.
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)
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.
这篇关于Altair交互式散点图锅添加日期滑块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!