Search code examples
colorsaltair

how to grey out other lines using Mouse hover?


I'm trying to grey out other lines when i hover over one of them so far i have this:

from sklearn import datasets
data_wine = datasets.load_wine (as_frame = True).frame
new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
hover = alt.selection(
   type="single", on="mouseover", fields=["variable"], nearest=True
)

lineplot = alt.Chart(new_data).mark_line().encode(
   alt.X("variable:N"),
   alt.Y("value:Q"),
   alt.Color ('target:N'),
   alt.Detail ('index:N'),
).properties(width = 1000)

# nearest point
point = lineplot.mark_circle().encode(
   opacity=alt.value(0)
).add_selection(hover)
# highlight
singleline = lineplot.mark_line().encode(
   size=alt.condition(~hover, alt.value(0.5), alt.value(3))
)


point+singleline

it looks like this and while hovering the mouse the size changes and i couldn't replace size with Color:

enter image description here

how can i achieve this?


Solution

  • new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
    new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
    
    highlight = alt.selection(type='single', on='mouseover', fields=['target'], nearest=False, bind='legend')
    
    selection = alt.selection_multi(fields=['target'], bind='legend', on='mouseover')
    
    lineplot=alt.Chart(new_data).mark_line().encode(
       alt.X("variable:N"),
       alt.Y("value:Q"),
       alt.Color ('target:N'),
       alt.Detail ('index:N'),
    ).properties(width = 1000)
    
    
    # nearest point
    point = lineplot.mark_circle().encode(
        opacity=alt.value(0)
    ).add_selection(highlight)
    #highlight
    singleline = lineplot.mark_line().encode(
       opacity=alt.condition(selection, alt.value(0.7), alt.value(0.03))
       #size=alt.condition(~highlight, alt.value(1), alt.value(3))
    ).add_selection(selection)
    
    
    point + singleline