Matplotlib图未显示在Jupyter笔记本第一个单元格的输出小部件中 [英] Matplotlib figure not showing up in output widget in first cell of Jupyter notebook
问题描述
在Jupyter笔记本的第一个单元格中有以下代码段:
I have the following snippet in the first cell of a Jupyter notebook:
import matplotlib.pyplot as plt
import pandas as pd
import ipywidgets as widgets
import numpy as np
out = widgets.Output()
data = pd.DataFrame(np.random.normal(size = 50))
plt.ioff()
with out:
fig, axes = plt.subplots()
data.hist(ax = axes)
display(fig)
plt.ion()
display(out)
如果我重新启动内核并运行第一个单元,则会看到以下输出:
If I restart the kernel and run this first cell, I see this output:
<Figure size 640x480 with 1 Axes>
但是,如果我在 second 时间内运行此第一个单元格,则会看到预期的matplotlib图形.如果在将matplotlib导入后将所有内容移动到第二个单元格,重新启动内核,然后重新运行整个笔记本,也会显示此行为.
However, if I run this first cell a second time, I see a matplotlib figure as I intended. This behavior also shows up if I move everything after the import of matplotlib to a second cell, restart the kernel, and rerun the entire notebook.
这种行为上的差异是故意的吗?
Is this difference in behavior intentional?
推荐答案
重新排列并添加魔术命令'%matplotlib notebook'的代码对我有用.
The code rearranging and adding magic command '%matplotlib notebook' work for me.
%matplotlib notebook
import matplotlib.pyplot as plt
import pandas as pd
import ipywidgets as widgets
import numpy as np
out = widgets.Output()
plt.ioff()
fig, axes = plt.subplots()
plt.ion()
data = pd.DataFrame(np.random.normal(size = 50))
data.hist(ax = axes)
display(out)
with out:
display(fig)
这篇关于Matplotlib图未显示在Jupyter笔记本第一个单元格的输出小部件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!