weidong
weidong

Reputation: 149

How to draw graphics dynamically on jupyterlab notebook

I found an example that can run normally on my laptop, but there is a problem. When the drawing is finished, a repeated result graph will be drawn again. I want to know how to not display the last repeated image.

import numpy as np
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt

# set up matplotlib
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
    from IPython import display

plt.ion()

def plot_durations(y):
    plt.figure(2)
    plt.clf()
    plt.subplot(211)
    plt.plot(y[:,0])
    plt.subplot(212)
    plt.plot(y[:,1])

    if is_ipython:
        display.clear_output(wait=True)
        display.display(plt.gcf())
        
x = np.linspace(-10,10,10)
y = []
for i in range(len(x)):
    y1 = np.cos(i/(3*3.14))
    y2 = np.sin(i/(3*3.14))
    y.append(np.array([y1,y2]))
    plot_durations(np.array(y))

plt.ioff() 
plt.show() 

Upvotes: 0

Views: 396

Answers (1)

BenB
BenB

Reputation: 658

Replacing plt.show() with plt.close() at the end of your code will prevent jupyter notebook from displaying the final plot twice. An explanation is included here.

Upvotes: 1

Related Questions