Search code examples
pythonaltair

Altair graph with conditional tooltip


I want to use 'tooltip' to show information depending on the type of point in the plot. I noticed that 'tooltip' accepts 'condition'. Therefore, I'm trying to use 'tooltip' together with 'alt.condition', but without success. Below is my attempt:

import altair as alt
from vega_datasets import data

source = data.cars()

chart = alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
    tooltip=alt.condition(
        alt.datum.Origin == 'EUA',
        ['Name', 'Horsepower'],
        ['Name', 'Miles_per_Gallon']
    )
)

chart.save('tooltip.html')

Is there any solution for this?


Solution

  • At the end of field section of the docs, it is mentioned that it is not possible to use a field/column as the value to be used if the condition is not met:

    Note: When using a conditional field definition, only value or datum may be specified as the else (outer) branch.

    It is also not possible to pass a list of values in a condition it seems like (a feature request could be opened for that in the VegaLite repo). Something like this does work:

    alt.Chart(source).mark_circle(size=60).encode(
        x='Horsepower',
        y='Miles_per_Gallon',
        color='Origin',
        tooltip=alt.condition(
            alt.datum.Origin == 'USA',
            'Name',
            alt.value('')
        )
    )