在 Jupyterlab 中居中 Altair 输出(包括导出到 HTML 时)

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

如何在 Jupyterlab 中居中对齐 Altair 图表,使其在导出的文件中保持居中 HTML?

以下代码将笔记本中的绘图居中;但是,当我将笔记本导出到 HTML 时,输出是 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))

如有任何帮助,我们将不胜感激!

很难确定如何回答您的问题,因为笔记本的显示和导出有很多变数(甚至在 jupyter notebook 和 jupyterlab 之间)。

我怀疑图表未在导出时显示的原因可能是因为您使用的是简单的 HTML 输出,它不适用于 requirejs,默认笔记本导出使用木星。

这有点 hack,但您可以访问默认笔记本 HTML 输出,无论是否使用 requirejs,它都可以工作,如下所示:

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

改用 HTML 应该可以在实时笔记本和 HTML 导出中工作:

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))