在Jupyterlab中居中Altair输出(包括将其导出为HTML时)

时间:2020-11-05 20:36:24

标签: jupyter-lab altair vega-lite

我如何在Jupyterlab中居中对齐Altair图表,以使其在导出的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'
)

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

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

我怀疑图表未显示在导出中的原因可能是因为您使用的是不兼容requirejs的简单HTML输出,Jupyter的默认笔记本导出使用了HTML。

这有点麻烦,但是您可以访问默认的笔记本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))