Matplotlib figure not showing up in output widget in first cell of Jupyter notebook

荒凉一梦 提交于 2019-12-23 09:08:02

问题


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>

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?


回答1:


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)


来源:https://stackoverflow.com/questions/50821003/matplotlib-figure-not-showing-up-in-output-widget-in-first-cell-of-jupyter-noteb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!