Consider the following example:
import altair as alt
from vega_datasets import data
import pandas as pd
stocks = data.stocks()
source = (
stocks.groupby([pd.Grouper(key="date", freq="6MS"), "symbol"])
.mean()
.reset_index()
)
hover_select = alt.selection_point(
name="hover_select", on="pointerover", empty=False
)
conditional_color = (
alt.when(hover_select)
.then(alt.Color("symbol:N"))
.otherwise(alt.value("lightgray"))
)
alt.Chart(source).mark_line(point=True).encode(
x=alt.X("date:O").timeUnit("yearmonth").title("date"),
y="rank:O",
color=conditional_color,
).add_params(hover_select).transform_window(
rank="rank()",
sort=[alt.SortField("price", order="descending")],
groupby=["date"],
).properties(
title="Bump Chart for Stock Prices",
width=600,
height=150,
)
If you hover over the points in the example, it will highlight the color of the lines, but not the points, which remain grey (except for the leftmost point).
How can we highlight the lines, based on whether the point is hovered?
In order for Altair to know that you want to highlight all items with the same symbol as the selection, you need to provide a fields
argument to the selection.
import altair as alt
from vega_datasets import data
import pandas as pd
stocks = data.stocks()
source = (
stocks.groupby([pd.Grouper(key="date", freq="6MS"), "symbol"])
.mean()
.reset_index()
)
hover_select = alt.selection_point(
name="hover_select", on="pointerover", empty=False, fields=["symbol"]
)
conditional_color = (
alt.when(hover_select)
.then(alt.Color("symbol:N"))
.otherwise(alt.value("lightgray"))
)
alt.Chart(source).mark_line(point=True).encode(
x=alt.X("date:O").timeUnit("yearmonth").title("date"),
y="rank:O",
color=conditional_color,
).add_params(hover_select).transform_window(
rank="rank()",
sort=[alt.SortField("price", order="descending")],
groupby=["date"],
).properties(
title="Bump Chart for Stock Prices",
width=600,
height=150,
)