8
votes

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
Can't reproduce this, neither with the classical jupyter notebook nor with jupyter lab. Can you provide your specs? - Daniel Lenz
@DanielLenz Ubuntu 16.04, Python 3.5.1 installed in a virtual environment, with Jupyter 4.4.0 and matplotlib 2.2.2 installed via pip. - Arthur Azevedo De Amorim
I have observed this behavior on Chromium and Firefox. - Arthur Azevedo De Amorim
What's the purpose of this nested structure? - ImportanceOfBeingErnest
@ImportanceOfBeingErnest I was trying to create a tab widget with plots on each tab, so I had to wrap the plots in output widgets. I removed the original tab to make the example simpler. - Arthur Azevedo De Amorim

1 Answers

3
votes

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)