Reputation: 871
I started playing around with Altair today and have a question about selections. I have created 3 bar charts with different colours as shown below. Now whenever I click on one bar, I'd like the equivalent to be highlighted in the other two bar charts. This works well if I don't use any colour and it defaults to blue, but I can't figure out how to keep my colours in the selection instead of having the same colour for all 3 charts.
df = pd.DataFrame({"Name":["Bulbasaur", "Charizard", "Mewtwo"],
"HP":[45, 80, 100],
"Attack":[30, 50, 60],
"Defense":[40, 38, 42],
"Type":["Grass", "Fire", "Psychic"]})
selection = alt.selection_single(fields=["Type 1"])
# This doesn't do much as I don't have a column named #73a1eb. But it's the colour code I'd like to use.
color1 = alt.condition(selection,
alt.Color("#73a1eb:N", legend=None),
alt.value('lightgray'))
color2 = alt.condition(selection,
alt.Color("#73b9c7:N", legend=None),
alt.value('lightgray'))
color3 = alt.condition(selection,
alt.Color("#d7abf5:N", legend=None),
alt.value('lightgray'))
# The mark bar colour is overriden by color in encode
chart1 = alt.Chart(df, title="Average HP by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(HP):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
chart2 = alt.Chart(df, title="Average Attack by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(Attack):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
chart2 = alt.Chart(df, title="Average Defense by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(Defense):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
alt.hconcat(chart1, chart2, chart3).configure_axis(grid=False).configure_axisBottom().resolve_scale(x = 'shared')
Upvotes: 1
Views: 2961
Reputation: 86310
When you write alt.Color("#73a1eb:N")
, it means you want the color to be encoded according to a column named "#73a1eb"
which has a nominal ("N"
) type.
It appears that you want to specify a color value rather than a color encoding, in which case you can write alt.value("#73a1eb")
. So your condition would look like this:
color1 = alt.condition(selection,
alt.value("#73a1eb"),
alt.value('lightgray'))
Upvotes: 4