pythonaltair

Is there a way to dynamically change the zorder of selected points in Altair?


I have an Altair plot with multiple points in similar xy position, similar to this plot in the Altair tutorial. Since I use tooltips, I'd like for the selected points to rise to the top (i.e. increase zorder in matplotlib terminology). Is there a way to do this? (If not, I'm happy to file a feature request!)


Solution

  • No, the z-order of the points is set by the order of each subchart within the layers, and this cannot be adjusted dynamically. This is fairly central to Vega-Lite's rendering model, and unlikely to be changed.

    One trick you can use to achieve what you want, though, is to overlay a duplicate chart which is filtered by the selection in question, to make selected points appear above all others. Here is an example:

    import altair as alt
    from vega_datasets import data
    
    cars = data.cars()
    
    selection = alt.selection_single(on='mouseover', nearest=True)
    
    base = alt.Chart(cars).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
        color=alt.condition(selection, 'Origin:N', alt.value('lightgray'))
    )
    
    alt.layer(
      base.add_selection(selection),
      base.transform_filter(selection).encode(tooltip='Name:N'),
    )
    

    Live Chart View