Center Altair output in Jupyterlab (including when it is exported to HTML)

It’s tough to know for certain how to answer your question, because there are so many variables in displaying and exporting of notebooks (even between, say, jupyter notebook and jupyterlab).

I suspect the reason the chart doesn’t show up on export is likely because you’re using a simple HTML output that doesn’t work with requirejs, which is used by the default notebook export in Jupyter.

This is a bit of a hack, but you can access the default notebook HTML output, which works with or without requirejs, like this:

with alt.renderers.enable('default'):
  html = c._repr_mimebundle_()['text/html']

Using that HTML instead should work in the live notebook and in the HTML export:

import altair as alt
import pandas as pd
from IPython.core.display import display, HTML

df=pd.DataFrame({'a': [1,2,3], 'b': [2,3,4]})

c=alt.Chart(df).mark_bar().encode(
    x='a',
    y='b'
)
with alt.renderers.enable('default'):
  html = c._repr_mimebundle_()['text/html']

s=f"""
<div style="display:flex;justify-content:center;align-items:center;width:100%;height:100%;">
  {html}
</div>
"""

display(HTML(s))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top