2
votes

Is it possible to change the position of a slider selection binding?

Couldn't find something in the altair documentation or in the vega-lite documentation (https://vega.github.io/vega-lite/docs/bind.html).

I want to move the year-slider up, closer to the main scatter plot:
https://vizsim.github.io/pkws_in_D/kba_neuzl_umwelt_fz14_v01.html

enter image description here

2

2 Answers

4
votes

The only way to adjust slider position in Altair/Vega-Lite output is to use CSS. If you're outputting HTML directly, you can add the CSS to the HTML file. If you're displaying an Altair chart within a Jupyter notebook, you can use the IPython.display module to add appropriate CSS.

For example, here is the US Population Over Time chart with the slider moved to the upper-right:

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
)

enter image description here

0
votes

You can also select and move it using JS. Here's the HTML with a separate column for the slider:

<div class="container">
  <div class="row">
    <div class="col-lg-8">
    <h3>Chart</h3>
    <div id="vis"></div>
    </div>
    <div class="col-lg">
    <h3>Slider</h3>
    <div id="slider">
      <div id="oldchildslider"></div>
    </div>
    </div>
  </div>
</div>

Now the JS to move the slider (with spec extracted from the Altair example):

vegaEmbed('#vis', spec).then(function(result) {
  const sliders = document.getElementsByClassName('vega-bindings'); 
  const newparent = document.getElementById('slider');  
  const oldchild = document.getElementById("oldchildslider");  
  newparent.replaceChild(sliders[0], oldchild);
}).catch(console.error);

Full code on Codepen: https://codepen.io/andyreagan/pen/xxgLwaZ?editors=1010 Reference to replaceChild method: https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild