Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Jupyter Notebook creating duplicate plots when making updating plots

I'm trying to make plots in a Jupyter Notebook that update every second or so. Right now, I just have a simple code which is working:

%matplotlib inline
import time
import pylab as plt
import numpy as np
from IPython import display

for i in range(10):
    plt.close()
    a = np.random.randint(100,size=100)
    b = np.random.randint(100,size=100)

    fig, ax = plt.subplots(2,1)
    ax[0].plot(a)
    ax[0].set_title('A')
    ax[1].plot(b)
    ax[1].set_title('B')

    display.clear_output(wait=True)
    display.display(plt.gcf())
    time.sleep(1.0)

Which updated the plots I have created every second. However, at the end, there is an extra copy of the plots:

enter image description here

Why is it doing this? And how can I make this not happen? Thank you in advance.

like image 419
TheStrangeQuark Avatar asked Apr 18 '16 03:04

TheStrangeQuark


People also ask

What is the difference between %Matplotlib inline and %Matplotlib notebook?

%matplotlib notebook will lead to interactive plots embedded within the notebook. %matplotlib inline will lead to static images of your plot embedded in the notebook.

What is %% Writefile in Jupyter notebook?

%%writefile lets you output code developed in a Notebook to a Python module. The sys library connects a Python program to the system it is running on. The list sys. argv contains the command-line arguments that a program was run with.

What does %% do in Jupyter notebook?

Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.

What does %Matplotlib Notebook mean?

%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


1 Answers

The inline backend is set-up so that when each cell is finished executing, any matplotlib plot created in the cell will be displayed.

You are displaying your figure once using the display function, and then the figure is being displayed again automatically by the inline backend.

The easiest way to prevent this is to add plt.close() at the end of the code in your cell.

like image 143
jakevdp Avatar answered Sep 21 '22 08:09

jakevdp