在 Altair/Vega-Lite 输出中调整滑块位置的唯一方法是使用 CSS。如果您直接输出 HTML,则可以将 CSS 添加到 HTML 文件中。如果您在 Jupyter 笔记本中显示 Altair 图表,则可以使用IPython.display module添加适当的 CSS。
例如,这里是美国人口随时间变化滑块移至右上角的图表:
from IPython.display import display, HTML
display(HTML("""
<style>
form.vega-bindings {
position: absolute;
right: 0px;
top: 0px;
}
</style>
"""))
import altair as alt
from vega_datasets import data
source = data.population.url
pink_blue = alt.Scale(domain=('Male', 'Female'),
range=["steelblue", "salmon"])
slider = alt.binding_range(min=1900, max=2000, step=10)
select_year = alt.selection_single(name="year", fields=['year'],
bind=slider, init={'year': 2000})
alt.Chart(source).mark_bar().encode(
x=alt.X('sex:N', title=None),
y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
color=alt.Color('sex:N', scale=pink_blue),
column='age:O'
).properties(
width=20
).add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)