Centering Altair charts in Jupyter Lab

altair
Author

ChuckPR

Published

January 13, 2025

Altair charts in Jupyter Lab are left-aligned by default.

import altair as alt
import pandas as pd
from bs4 import BeautifulSoup
from IPython.display import HTML, Markdown
from vega_datasets import data
df_co2 = data.co2_concentration()

df_co2.head()
Date CO2
0 1958-03-01 315.70
1 1958-04-01 317.46
2 1958-05-01 317.51
3 1958-07-01 315.86
4 1958-08-01 314.93
ax = alt.Axis(
    titleFontSize=16, titleFontWeight="normal", titlePadding=15, labelFontSize=12
)

c = (
    alt.Chart(df_co2, width=500)
    .mark_line()
    .encode(
        x=alt.X("Date:T", axis=ax), y=alt.Y("CO2", scale=alt.Scale(zero=False), axis=ax)
    )
)

c

I often want to center charts horizontally. One quick hack to do this is setting the Altair chart div CSS justify-content property to center (see docs here).

This is the style tag for our chart with the default Altair render:

soup = BeautifulSoup(c._repr_mimebundle_()["text/html"], "html.parser")

Markdown(f"```css\n{str(soup.style)}\n```")
<style>
  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed {
    width: 100%;
    display: flex;
  }

  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed details,
  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed details summary {
    position: relative;
  }
</style>

We can set the justify-content property by appending to the style tag:

soup.style.append(f'  #{soup.div["id"]}.vega-embed {{justify-content: center;}}\n')

Markdown(f"```css\n{str(soup.style)}\n```")
<style>
  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed {
    width: 100%;
    display: flex;
  }

  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed details,
  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed details summary {
    position: relative;
  }
  #altair-viz-de18aeebcbdb4ebba576b24dd3cc8b7e.vega-embed {justify-content: center;}
</style>

To visualize the centered chart, create an HTML display object with the updated html:

HTML(str(soup))