Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a residual plot in Jupyter output after displaying a matplotlib animation?

I want to display an animation in Jupyter using Matplotlib. Here is some basic example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)


def update(data):
    line.set_ydata(data)
    return line,


def data_gen():
    while True:
        yield np.random.rand(10)

ani = animation.FuncAnimation(fig, update, data_gen, interval=100);

from IPython.display import HTML
HTML(ani.to_jshtml())

When I run the code for the first time (or after restarting the kernel) I get what I want: enter image description here

However, when I run the very same code for the second time I get a leftover in the left bottom: enter image description here

I noticed that when I add %matplotlib inline at the top, then I got the bad output even after restarting the kernel. Thus my guess is that I have to set the magic command %matplotlib to default at the top each time I create an animation, but I can't even find if %matplotlib have a default value.


I use Anaconda. Here are my versions: Conda version: 4.4.10 Python version: Python 3.6.4 :: Anaconda, Inc. IPython version: 6.2.1 Jupyter version: 5.4.0

like image 773
Fallen Apart Avatar asked May 11 '18 09:05

Fallen Apart


1 Answers

enter image description here

I used plt.close() to stop the first (unwanted) plot, and have not seen issues running the animation in a separate cell. I believe the issue is similar to those linked in the comments, jupyter is automatically displaying an unwanted plot for the first two lines - fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10)). I tired suggestions such as using semicolons at end of lines and a few different magic attempts, but no joy. A more concrete solution will no doubt appear, but for now....

like image 124
10SecTom Avatar answered Oct 18 '22 18:10

10SecTom