Altair Themes: Change the Look of Every Chart

Use Altair's built-in themes, register a custom theme with alt.theme.register(), override it per chart, and switch back to the default.

Turn on a built-in Altair theme with alt.theme.enable("fivethirtyeight"), or define your own with the @alt.theme.register() decorator. A theme applies to every chart rendered afterward. This post uses the alt.theme module, added in Altair 5.5, on Altair 6.2.

Quick Example

A theme is a function that returns a Vega-Lite configuration. Register it once and your charts pick it up.

import altair as alt
import numpy as np
import pandas as pd

# Sample data: weekend visitors at a ski area over one season.
rng = np.random.default_rng(29)
weekends = np.arange(1, 17)
season = 900 + 2300 * np.sin(np.pi * weekends / 17)
visitors = pd.concat([
    pd.DataFrame({
        "weekend": weekends,
        "ticket": name,
        "visitors": (season * share + rng.normal(0, 70, 16)).round().astype(int),
    })
    for name, share in [("Season pass", 0.55), ("Day ticket", 0.32), ("Lesson", 0.13)]
])


@alt.theme.register("alpine", enable=True)
def alpine():
    return alt.theme.ThemeConfig({
        "background": "#f6f8fb",
        "padding": 16,
        "config": {
            "font": "Georgia",
            "title": {"fontSize": 20, "anchor": "start", "color": "#102a43",
                      "offset": 14},
            "axis": {"labelColor": "#486581", "titleColor": "#486581",
                     "labelFontSize": 12, "titleFontSize": 13,
                     "gridColor": "#d9e2ec", "domain": False, "ticks": False},
            "legend": {"orient": "top", "title": None, "labelFontSize": 12},
            "range": {"category": ["#1f4e79", "#4ea8de", "#e76f51"]},
            "view": {"stroke": None},
            "bar": {"cornerRadiusEnd": 2},
        },
    })


chart = alt.Chart(visitors, width=480, height=280, title="Visitors by weekend").mark_bar().encode(
    x=alt.X("weekend:O", title="Weekend of the season", axis=alt.Axis(labelAngle=0)),
    y=alt.Y("visitors:Q", title=None),
    color="ticket:N",
)
chart

Stacked Altair bar chart of weekend ski visitors with a custom theme: pale blue background, Georgia font, navy, sky blue and coral bars, and the legend on top

Nothing in the chart code mentions colors or fonts. enable=True switches the theme on as it's registered.

Use a Built-in Theme

alt.theme.names() lists what's available, and alt.theme.enable() picks one.

print(alt.theme.names())

alt.theme.enable("fivethirtyeight")
chart

Altair 6.2 includes carbong10, carbong100, carbong90, carbonwhite, dark, default, excel, fivethirtyeight, ggplot2, googlecharts, latimes, opaque, powerbi, quartz, urbaninstitute, and vox, plus none and any you register. Here's the same chart in six of them:

The ski visitor chart repeated in the default, dark, fivethirtyeight, ggplot2, latimes and vox themes

Some of these ask for fonts you may not have. urbaninstitute uses Lato, and when I exported it to PNG without Lato installed, the text disappeared.

The theme is applied when a chart is displayed or saved, not when you create it. chart was built under alpine, and showing it again after enable() gives the new look.

What Can a Theme Set?

The dictionary mirrors the Vega-Lite spec. Most styling goes under "config":

Key under config Controls
font the typeface for all text
title chart title size, color, and position
axis, axisX, axisY labels, grid, ticks, and domain line
legend position, title, and label style
range default color sets: category, ordinal, ramp, heatmap, diverging
mark, bar, line, point default mark properties
view the plot area's border and fill

background, padding, width, and height sit at the top level. alt.theme.ThemeConfig is a typed dictionary, so an editor can autocomplete the keys.

A font has to be available wherever the chart renders. Web fonts need to be loaded by the page, and PNG export needs the font installed on your computer.

Make a Dark Theme From the Same Function

A small factory function avoids copying the dictionary for light and dark versions.

def make_theme(background, text, grid, colors):
    def theme():
        return alt.theme.ThemeConfig({
            "background": background,
            "padding": 16,
            "config": {
                "title": {"color": text, "fontSize": 18, "anchor": "start"},
                "axis": {"labelColor": text, "titleColor": text, "gridColor": grid,
                         "domain": False, "ticks": False},
                "legend": {"labelColor": text, "titleColor": text, "orient": "top"},
                "range": {"category": colors},
                "view": {"stroke": None},
            },
        })
    return theme


alt.theme.register("night", enable=True)(make_theme(
    background="#101820", text="#e6edf3", grid="#2b3a47",
    colors=["#7bdff2", "#f7d6e0", "#f2b134"]))
chart

The ski visitor chart on a near-black background with light text and pastel blue, pink and gold bars

Override the Theme for One Chart

configure_* methods set the same options on a single chart, and they win over the theme. Anything set directly on a mark or encoding wins over both.

override = chart.configure_axis(grid=False).configure_title(color="#f2b134")
override

The dark themed chart with gridlines removed and a gold title

Settings the chart doesn't override still come from the theme. Call configure_* last: a chart that already has a config can't be layered or concatenated, and Altair raises TypeError: Objects with 'config' attribute cannot be used within LayerChart.

Switch Themes Temporarily or Reset

Use enable() as a context manager to style one block of code, then return to whatever was active.

with alt.theme.enable("quartz"):
    chart.save("quartz-chart.png", scale_factor=2)

print(alt.theme.active)  # night

alt.theme.enable("default")

"default" restores Altair's standard look. "none" removes Altair's default view size too, leaving plain Vega-Lite defaults.

Share a Theme Across Projects

Put the registered function in a module, such as chart_theme.py:

import altair as alt


@alt.theme.register("company", enable=True)
def company():
    return alt.theme.ThemeConfig({
        "config": {"range": {"category": ["#1f4e79", "#4ea8de", "#e76f51"]}},
    })

Then import chart_theme in any notebook or script to apply it. Importing runs the decorator, which registers and enables the theme.

Practical Tips

  • alt.themes (plural) is the old API, deprecated since Altair 5.5. Replace alt.themes.enable() with alt.theme.enable().
  • Define colors in range.category instead of passing a scale on every chart.
  • Use configure_* for one-off changes and a theme once you've repeated a setting twice.
  • Check a theme on a bar chart, a line chart, and a heatmap, since each uses different parts of the config.
  • Streamlit applies its own theme to st.altair_chart. Pass theme=None to keep yours.

Similar Topics