How would I center align an Altair chart in Jupyterlab so that it remains centered in the exported HTML?
The following code centers the plot in the notebook; however, when I export the notebook to HTML, the output is empty/blank.
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'
)
s=f"""
<div style="display:flex;justify-content:center;align-items:center;width:100%;height:100%;">
<div>{c.to_html()}</div>
</div>
"""
display(HTML(s))
Any help would be much appreciated!
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))