I am trying to create an Altair chart with a checkbox. By default the checkbox is unchecked, but I would like the default to be checked. The HTML checkbox has the "checked" attribute to achieve this, but I do not know how to convey this via the Altair API. Is this possible?
In the example below, the "A" and "B" series start colored, and the checkboxes are not checked. The desired behavior would be for the boxes to be checked, and when they are unchecked the corresponding series would be grayed out.
data = pd.DataFrame(
{
"Block":("A", "A", "B", "A", "B", "A"),
"X":(10, 15, 11, 30, 45, 9),
"Y":(1.1, 10, 3.5, 5, 10, 20),
}
)
a_data = data.loc[data["Block"] == "A"]
b_data = data.loc[data["Block"] == "B"]
a_filter = alt.binding_checkbox()
b_filter = alt.binding_checkbox()
a_select = alt.selection_single(
fields=["Block"], bind=a_filter, name="A"
)
b_select = alt.selection_single(
fields=["Block"], bind=b_filter, name="B"
)
a_cond = alt.condition(
a_select, alt.Color("Block:N"), alt.value("lightgray")
)
b_cond = alt.condition(
b_select, alt.Color("Block:N"), alt.value("lightgray")
)
a_chart = alt.Chart(a_data).mark_point(filled=True).encode(
x="X:Q",
y=alt.Y(
"Y:Q", scale=alt.Scale(type="log")
),
color=a_cond
).add_selection(a_select)
b_chart = alt.Chart(b_data).mark_point(filled=True).encode(
x="X:Q",
y=alt.Y(
"Y:Q", scale=alt.Scale(type="log")
),
color=b_cond
).add_selection(b_select)
(a_chart + b_chart)
Example chart
Altair version 2 (the current version) does not support selection defaults.
Altair version 3 (which will be released very soon) does support selection defaults, using the init parameter, which you will be able to use like this:
a_select = alt.selection_single(
fields=["Block"], bind=a_filter, name="A", init={'Block': 'A'}
)
b_select = alt.selection_single(
fields=["Block"], bind=b_filter, name="B", init={'Block': 'B'}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With