bzm3r
bzm3r

Reputation: 4605

Highlight color of both point and line in a line plot with point markers?

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?

Upvotes: 1

Views: 24

Answers (1)

kgoodrick
kgoodrick

Reputation: 883

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.

enter image description here

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,
)

Upvotes: 1

Related Questions