Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Altair Condition Color Opacity

In an Altair condition I want to specify the opacity for the the secondary conditional color. My data in the scatter are fairly dense so I want the unselected points to go away (more or less).

Using the example from here, I want this code:

selection = alt.selection_multi(fields=['Origin'])
color = alt.condition(selection,
                   alt.Color('Origin:N', legend=None),
                   alt.value('lightgray') # WANT THIS TO BE %50 OPACITY
)

scatter = alt.Chart(cars).mark_point().encode(
 x='Horsepower:Q',
 y='Miles_per_Gallon:Q',
 color=color,
 tooltip='Name:N'
)

legend = alt.Chart(cars).mark_point().encode(
 y=alt.Y('Origin:N', axis=alt.Axis(orient='right')),
 color=color
).add_selection(
 selection
)

scatter | legend

to have the color condition be like:

color = alt.condition(selection,
                   alt.Color('Origin:N', legend=None),
                   alt.Color(value='lightgray', opacity=0.5)
)

However I can't seem to figure it out and there doesn't appear to be any solution online.

Thanks!

like image 520
wiestyfbaby Avatar asked Mar 03 '23 01:03

wiestyfbaby


1 Answers

The opacity is a separate channel, so you can put a condition on both the color and the opacity:

color = alt.condition(selection,
                      alt.Color('Origin:N', legend=None),
                      alt.value('lightgray'))
opacity = alt.condition(selection, alt.value(1.0), alt.value(0.5))

scatter = alt.Chart(cars).mark_point().encode(
 x='Horsepower:Q',
 y='Miles_per_Gallon:Q',
 color=color,
 opacity=opacity,
 tooltip='Name:N'
)
like image 111
jakevdp Avatar answered Mar 05 '23 15:03

jakevdp