2

I have successfully created an interactive chart as the tutorial here and below is my result:

enter image description here

I want to create a tooltip as the image below: enter image description here

But I cannot find any hint in Altair tutorial document.

Can anyone provide a suggestion about how to proceed?

Sang Huynh
  • 41
  • 3

1 Answers1

4

You can create a single tooltip for multiple lines using the pivot transform. Here is an example using one of the vega datasets.

THe idea is that the tooltip is tied to the vertical rule mark, which represents a pivoted version of the data where each relevant value is in the same row:

import altair as alt
from vega_datasets import data

source = data.stocks()
base = alt.Chart(source).encode(x='date:T')
columns = sorted(source.symbol.unique())
selection = alt.selection_single(
    fields=['date'], nearest=True, on='mouseover', empty='none', clear='mouseout'
)

lines = base.mark_line().encode(y='price:Q', color='symbol:N')
points = lines.mark_point().transform_filter(selection)

rule = base.transform_pivot(
    'symbol', value='price', groupby=['date']
).mark_rule().encode(
    opacity=alt.condition(selection, alt.value(0.3), alt.value(0)),
    tooltip=[alt.Tooltip(c, type='quantitative') for c in columns]
).add_selection(selection)

lines + points + rule

enter image description here

jakevdp
  • 77,104
  • 11
  • 125
  • 160