Search code examples
pythonjupyter-notebookselectionaltairvega-lite

In altair: how to assign individual placements to selection elements (dropdown lists etc) in a concatenated plot


This is a follow up question to: On an Altair plot, can you change the location that a selection (e.g. dropdown, radio button) is displayed?

I have the situation, that I've got a horizontally concatenated chart, where I use a dropdown selector for the left and another one for the right plot. Now I would like either list to appear underneath their respective plot.

Currently they both appear on top of each other, and with the solution from the link above I can move them together from left to right. Is there a way to separate them?

I don't know whether that's something altair can do, i.e. whether the preconditions in vega-lite allow for that.


Solution

  • One way you might do this is to use the same strategy as the linked question, but with the Subsequent Sibling combinator in CSS. For example:

    import altair as alt
    from vega_datasets import data
    
    input_dropdown1 = alt.binding_select(options=['Europe','Japan','USA'], name='chart1')
    selection1 = alt.selection_single(fields=['Origin'], bind=input_dropdown1)
    
    chart1 = alt.Chart(data.cars.url).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
        color = alt.condition(selection1, 'Origin:N', alt.value('lightgray')),
        tooltip='Name:N'
    ).add_selection(
        selection1
    )
    
    input_dropdown2 = alt.binding_select(options=['Europe','Japan','USA'], name='chart2')
    selection2 = alt.selection_single(fields=['Origin'], bind=input_dropdown2)
    
    chart2 = alt.Chart(data.cars.url).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
        color = alt.condition(selection2, 'Origin:N', alt.value('lightgray')),
        tooltip='Name:N'
    ).add_selection(
        selection2
    )
    
    from IPython.display import HTML
    display(HTML("""
    <style>
    .vega-bind {
      text-align:right;
    }
    .vega-bind ~ .vega-bind {
      text-align:left;
    }
    </style>
    """))
    display(chart1 | chart2)
    

    enter image description here