DEV Community

João Palmeiro
João Palmeiro

Posted on

4 2

How to change a tooltip to dark theme in Altair?

When we add a tooltip to a chart in Altair, as in the example below, it follows a light theme by default. This tooltip implementation comes from Vega Tooltip, a plugin included in Vega-Embed (the package used under the hood to render the charts).

import altair as alt
import pandas as pd

source = pd.DataFrame(
    {
        "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
        "b": [28, 55, 43, 91, 81, 53, 19, 87, 52],
    }
)

alt.Chart(source).mark_bar(tooltip=True).encode(x="a", y="b")
Enter fullscreen mode Exit fullscreen mode

Example of a light-themed tooltip in an Altair chart

In addition to the light theme, Vega Tooltip also has another predefined theme: the dark theme. To use the dark theme, let's set one of the Vega-Embed options to do so, similar to when we configured Vega-Embed for a single Altair chart:

metadata = {"embedOptions": {"tooltip": {"theme": "dark"}}}
Enter fullscreen mode Exit fullscreen mode

Now, considering the chart we created at the beginning, we just need to pass the dictionary defined above as an argument to the properties() method:

alt.Chart(source).mark_bar(tooltip=True).encode(x="a", y="b").properties(
    usermeta=metadata
)
Enter fullscreen mode Exit fullscreen mode

As a result, the tooltip will look like this:

Example of a dark-themed tooltip in an Altair chart

On the other hand, to enable the dark theme globally for all charts in a notebook, for example, it is a matter of running the following snippet initially:

alt.renderers.set_embed_options(tooltip={"theme": "dark"})
Enter fullscreen mode Exit fullscreen mode

Finally, if you have any questions or suggestions, feel free to leave a comment below!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more