是否可以创建Altair绑定到数据列表元素而不是select?

问题描述 投票:1回答:1

我正在尝试在时间序列图上设置基因表达的交互式过滤器。创建此类过滤器的记录方法是将select_single绑定到输入表单。对于较少数量的选项,binding_select将起作用。例如:

import altair as alt
group_dropdown = alt.binding_select(options=gene_names)
group_select = alt.selection_single(fields=['gene'], bind=group_dropdown, name='Feature', init={'gene': gene_names[0]})
filter_group = chart.add_selection(group_select).transform_filter(group_select)

但是,我可以选择约50K个基因,因此下拉列表(binding_select)并不是真正的选择。一个<datalist>元素将是完美的。 Input Binding上的vega-lite文档暗示我应该能够使用任何HTML表单输入元素,但我无法弄清楚将映射到该元素的Altair类。

python plot interactive vega-lite altair
1个回答
0
投票

这是可能的,但是由于两个原因有些困难:

  • 尽管Vega支持任意参数以形成输入,但vega-lite的架构禁止此类参数。这意味着您需要解决Altair的常规验证机制才能使用它。
  • <datalist>必须注入到图表的HTML输出中,并且没有很好的机制来做到这一点。

这里是一个示例,说明了如何解决这些限制并在Altair选择输入绑定中使用数据列表:

from IPython.display import HTML, display

import altair as alt
from vega_datasets import data

from altair.utils.display import HTMLRenderer
from altair.utils import schemapi

datalist = """
<datalist id="origin">
  <option value="USA">
  <option value="Europe">
  <option value="Japan">
</datalist>
"""

# Allow specifications that are invalid according to the schema.
# This prevents a validation error for the `list` argument below.
schemapi.DEBUG_MODE = False
# `list` here should match the ID of the <datalist> specification.
widget = alt.binding(input='text', name='Country', list='origin')

# now create the chart as normal:
selection = alt.selection_single(fields=['Origin'], bind=widget)
color = alt.condition(selection,
                    alt.Color('Origin:N', legend=None),
                    alt.value('lightgray'))
chart = alt.Chart(data.cars.url).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color=color,
    tooltip='Name:N'
).add_selection(
    selection
)

# Note the following assumes the default renderer.
alt.renderers.enable('default')

# Render the chart to HTML without validating it against the schema:
renderer = alt.renderers.get()
html = renderer(chart.to_dict(validate=False))['text/html']

# Now display the datalist and chart rendering:
display(HTML(datalist + html))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.