该问题是由于Altair图表默认使用Javascript的鼠标事件来实现交互,而触摸屏设备不支持这些事件导致的。解决该问题的方法是使用Vega-Lite的Tap事件来替代鼠标事件。具体代码实现如下:
import altair as alt
from vega_datasets import data
source = data.cars()
chart = alt.Chart(source).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
)
# 使用Tap事件来实现交互
chart = chart.interactive().properties(
selection=alt.selection_single(),
width='container',
height='container'
).transform_filter(
alt.datum['Horsepower'] > 100
).add_selection(
alt.selection(type='interval', encodings=['x'])
)
chart = chart.configure_touch(
view='panZoom',
move=False # 禁用移动事件以避免与Tap事件冲突
)
chart
在上述代码中,通过使用Vega-Lite的Tap事件来替代鼠标事件,并且使用chart.configure_touch()方法来设置触摸屏设备的交互行为,最终解决了Altair交互式图变成静态图的问题。