import altair as alt
import pandas as pd
from bs4 import BeautifulSoup
from IPython.display import HTML, Markdown
from vega_datasets import data
Centering Altair charts in Jupyter Lab
altair
Altair charts in Jupyter Lab are left-aligned by default.
= data.co2_concentration()
df_co2
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 |
= alt.Axis(
ax =16, titleFontWeight="normal", titlePadding=15, labelFontSize=12
titleFontSize
)
= (
c =500)
alt.Chart(df_co2, width
.mark_line()
.encode(=alt.X("Date:T", axis=ax), y=alt.Y("CO2", scale=alt.Scale(zero=False), axis=ax)
x
)
)
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:
= BeautifulSoup(c._repr_mimebundle_()["text/html"], "html.parser")
soup
f"```css\n{str(soup.style)}\n```") Markdown(
>
<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:
f' #{soup.div["id"]}.vega-embed {{justify-content: center;}}\n')
soup.style.append(
f"```css\n{str(soup.style)}\n```") Markdown(
>
<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:
str(soup)) HTML(