notebook
渲染器,以便包括plotly javascript捆绑包(也许这就是您的图形未显示的原因)。有关plotly渲染器的文档,请参见https://plot.ly/python/renderers/。然后,您可以使用各种解决方案将HTML包含在Sphinx文档中(请参见在Sphinx文档中包含独立的HTML页面)。这个图表本身是一个嵌入在jupyter笔记本文件中的HTML。您可以在任何文本编辑器中打开notebook.ipnb文件,找到图表HTML开始的位置,将所有HTML复制到html文件中并保存,例如a.html,然后只需在RST文档中插入原始html即可。
.. raw::
:file: a.html
html_js_files = [
"require.min.js", # Add to your _static
"custom.js",
]
示例 custom.js:
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-2.12.1.min.js?noext',
},
});
这样做
在尝试了许多解决方法后,对我有效的解决方案是在笔记本的开头添加这些行。
import plotly
plotly.offline.init_notebook_mode()
对于我来说,涉及修改conf.py
中的选项nbsphinx_prolog
、nbsphinx_requirejs_options
和html_js_files
的解决方案都不起作用。
我正在使用sphinx_rtd_theme
HTML主题和以下版本:
nbsphinx==0.8.9
sphinx-autobuild==2021.3.14
sphinx==4.4.0
通过使用Python,您可以使用plotly.tools.get_embed函数生成HTML代码来嵌入Plotly图形。
import plotly.tools as tls
tls.get_embed('https://plot.ly/~chris/1638')
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
然后页面将会重新启动。
.. jupyter-execute::
import plotly.graph_objects as go
trace = go.Scatter(
x=[0, 1, 2, 3, 4],
y=[0, 1, 4, 9, 16],
)
layout = go.Layout(title='Growth')
figure = go.Figure(data=[trace], layout=layout)
figure.show()
.. jupyter-execute::
:hide-code:
# 创建图形##已删除以缩短篇幅
img_bytes = fig.to_image(format="png")
Image(img_bytes)
- Matt Ruge在你的笔记本顶部尝试这个:
import plotly.io as pio
pio.renderers.default = "sphinx_gallery"
这个渲染器确保您的笔记本电脑(或单元格输出,或其他什么,不确定!)包括您的单元格输出需要呈现绘图所需的JavaScript资源。
其他渲染器或设置也可能实现此目的。但到目前为止,这是我尝试过的唯一一个渲染器,在其中我可以使用sphinx(实际上是jupyter book)构建笔记本,并且交互式绘图显示在构建中。
output_type ='div'
输出HTML。 - J63FigureWidget
下更容易了。如果有兴趣,我可以准备一个答案。 - astrojuanlu