BugSquanch
BugSquanch

Reputation: 326

altair can't create combination of selections

I want to create an interactive 'legend' that allows me to select combinations of the data in different columns. For example if we have this data:

data = {
    'type1': [1, 0, 0, 1, 0, 1],
    'type2': [1, 1, 1, 1, 0, 0],
    'type3': [1, 0, 0, 1, 1, 0],
    'id': ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'],
    'fuel': [1, 10, 30, 50, 25, 20]
}
df = pd.DataFrame(data, columns=['id', 'fuel', 'type1', 'type2', 'type3'])

which results in:
image

I now want the ability to visualize the combinations of different 'types'.
Something like this:
image
So if I toggle only type1, only test6 should be shown.
If I toggle all the types, only test4 and test1 should be shown.
The ideal solution would be to do this with a single legend, is it possible to achieve this?
Also Is this possible to achieve this with multiple charts like I am trying to do in the image above?
I can't seem to figure this out.

Upvotes: 1

Views: 1007

Answers (1)

jakevdp
jakevdp

Reputation: 86433

One way to do this is to create a selection per column, bound to a checkbox. For example:

import altair as alt
import pandas as pd

data = {
    'type1': [1, 0, 0, 1, 0, 1],
    'type2': [1, 1, 1, 1, 0, 0],
    'type3': [1, 0, 0, 1, 1, 0],
    'id': ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'],
    'fuel': [1, 10, 30, 50, 25, 20]
}

sel = [
  alt.selection_single(bind=alt.binding_checkbox(name=field), fields=[field], init={field: False})
  for field in ['type3', 'type2', 'type1']
]

df = pd.DataFrame(data, columns=['id', 'fuel', 'type1', 'type2', 'type3'])

alt.Chart(df).transform_calculate(
    type1='toBoolean(datum.type1)',
    type2='toBoolean(datum.type2)',
    type3='toBoolean(datum.type3)',
).mark_point().encode(
    x='id',
    y='fuel',
    opacity=alt.condition(sel[0] & sel[1] & sel[2], alt.value(1), alt.value(0))
).add_selection(
    *sel
)

enter image description here

Upvotes: 2

Related Questions