Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 485
Arthur Azevedo De Amorim Avatar asked Jun 12 '18 15:06

Arthur Azevedo De Amorim


People also ask

How do you display plots in Jupyter notebook?

The inline option with the %matplotlib magic function renders the plot out cell even if show() function of plot object is not called. The show() function causes the figure to be displayed below in[] cell without out[] with number. Now, add plt. show() at the end and run the cell again to see the difference.

What is matplotlib use (' AGG ')?

The last, Agg, is a non-interactive backend that can only write to files. It is used on Linux, if Matplotlib cannot connect to either an X display or a Wayland display.

How do I make matplotlib work in Jupyter?

Install Matplotlib Make sure you first have Jupyter notebook installed, then we can add Matplotlib to our virtual environment. To do so, navigate to the command prompt and type pip install matplotlib. Now launch your Jupyter notebook by simply typing jupyter notebook at the command prompt.


Video Answer


1 Answers

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)
like image 199
alz Avatar answered Oct 10 '22 04:10

alz