python - 在带有 ipywidgets 的 jupyter notebook 上使用 nbconvert 时,输出小部件出现在选项卡小部件之外

标签 python html jupyter-notebook ipywidgets nbconvert

我创建了一个笔记本,它应该在选项卡小部件中显示绘图。据我了解,要在选项卡小部件中包含诸如绘图之类的内容,我需要将其包装在输出小部件中。在笔记本本身中它可以工作,但是当我通过 nbconvert 将其转换为 html 时,它会产生错误的输出。

slider 、按钮或文本之类的小部件出现在它们应该出现在选项卡小部件中的位置,但是当我使用输出小部件捕获绘图(甚至是 print() 函数中的一些文本)时,它出现在选项卡环境之前,该环境本身为空.

这是每个选项卡一个图的外观(在笔记本中工作):
Plots in tabs within notebook

这就是它在 nbconvert 之后的样子(在 html 中)。这些图出现在选项卡环境之前:
Plots before tabs in html

请注意,nbconvert 包括其他小部件以及其他内容的选项卡。

这是使用的代码:

# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets as widgets
import numpy as np

# Generated data for plotting
data = pd.DataFrame()
for i in range(5):
    data[i] = np.random.normal(size = 50)

现在这部分可以在笔记本中使用,但不能在 html 中使用,但正如您将看到的,它似乎与输出小部件有关,因为我不使用绘图或打印文本。

# This does not work with plots
children = []
for i in range(data.shape[1]):
    out = widgets.Output()
    with out:
        fig, axes = plt.subplots()
        data[i].hist(ax = axes)
        plt.show()
    children.append(out)
tab = widgets.Tab()
tab.children = children
for i in range(len(children)):
    tab.set_title(i, "Plot " + str(i))
tab

# And this does not work with printed output
children = []
for i in range(5):
    out = widgets.Output()
    with out:
        print("This is text", i)
    children.append(out)
tab = widgets.Tab()
tab.children = children
for i in range(len(children)):
    tab.set_title(i, "Text " + str(i))
tab

但是,如果我使用不同的小部件类型(例如文本),它会正确显示在笔记本和 nbconvert 的 html 输出中。

# This works with the Text widget
children = []
for i in range(5):
    out = widgets.Text(description="P"+str(i))
    children.append(out)
tab = widgets.Tab()
tab.children = children
for i in range(len(children)):
    tab.set_title(i, "Text " + str(i))
tab

那么,有什么我可以改变以使其真正起作用的吗?我最终需要的是一种在 N 个选项卡中显示 N 个图的方法......

最佳答案

我有同样的问题。更新nbconvert (例如通过 pip install --upgrade nbconvert )解决了它。
引自 https://github.com/jupyter/nbconvert/issues/923 :

MSeal commented on 2020-09-07:

Yes, this issue was resolved in jupyter/nbclient#24 and nbclient >= 0.4.0 has the fix. NBconvert 6.0 (which should be releasing tomorrow) defaults to using nbclient and the issue overall should disappear. You can try it out on the 6.0.0rc0 release today if you like.

关于python - 在带有 ipywidgets 的 jupyter notebook 上使用 nbconvert 时,输出小部件出现在选项卡小部件之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285733/

相关文章:

python - 如何修复 pylint E1134 : Non-mapping value X is used in a mapping context (not-a-mapping)

python - 使用 Python 请求库构建 URL

php - Opencart修改系统相关问题

javascript - 包含 javascript 的最有效方法?

python - 更改 Python 可执行文件

python - 如何在构建期间生成 python 代码并将它们包含在 python 轮中?

Python AUTH0 发布请求 : Invalid request payload JSON format

javascript - 子元素及其父元素的鼠标滚轮处理程序

python - 绘制几年的日期时间,但在 x 轴上仅显示十二个月

python - 无法访问docker容器内的jupyter笔记本