【发布时间】:2019-11-11 18:58:21
【问题描述】:
我正在尝试以编程方式生成笔记本,执行它,然后使用 nbformat 转换为 HTML。
代码基本上是这样的:
import nbformat as nbf
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert import HTMLExporter
nb = nbf.v4.new_notebook()
nb.cells = [nbf.v4.new_code_cell("""
import altair as alt
alt.renderers.enable("notebook")
# ... load df
alt.Chart(df).mark_point().encode(x='x', y='y')
""")]
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
ep.preprocess(nb, {'metadata': {'path': '.'}})
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(nb)
with open('out.html', 'w') as f:
f.write(body)
流程运行良好,它生成一个笔记本和一个 HTML 文件,所有代码都已执行。但是,代码单元格的输出如下(无图表):
<vega.vegalite.VegaLite at 0x7f80c4d8a090>
当我将 notebook 写为 .ipynb 文件并手动执行时,在相同的环境中,图表按预期显示。是否可以通过这种方式使用 Altair?我想知道我在 Python 会话中运行 nbformat 是否会有所不同,也许它只能在浏览器中呈现图表?
【问题讨论】:
标签: python jupyter-notebook jupyter altair