Home>

I'm trying to do a python animation, but it doesn't work.
I couldn't understand it for about 3 hours.
I would like someone to tell me.

Error message

raceback (most recent call last):
File "C: \ Users \ haird \ Miniconda3 \ lib \ site-packages \ matplotlib \ cbook \init.py", line 216, in process
func (* args, ** kwargs)
File "C: \ Users \ haird \ Miniconda3 \ lib \ site-packages \ matplotlib \ animation.py", line 953, in _start
self._init_draw ()
File "C: \ Users \ haird \ Miniconda3 \ lib \ site-packages \ matplotlib \ animation.py", line 1732, in _init_draw
self._draw_frame (next (self.new_frame_seq ()))
File "C: \ Users \ haird \ Miniconda3 \ lib \ site-packages \ matplotlib \ animation.py", line 1758, in _draw_frame
raise RuntimeError ('The animation function must return a'
RuntimeError: The animation function must return a sequence of Artist objects.

Applicable source code
% matplotlib inline
import random
fig = plt.figure ()
xlim = [0,100]
X, Y = [], []
def plot (data):
    plt.cla () # delete previous graph
    Y.append (random.random ()) # create data
    X.append (len (Y))
    if len (X)>100: # update drawing range
        xlim [0] + = 1
        xlim [1] + = 1
    plt.plot (X, Y) # create next graph
    plt.title ("sample animation (real time)")
    plt.ylim (-1,2)
    plt.xlim (xlim [0], xlim [1])

# Create animation by calling plot function every 10ms
ani = animation.FuncAnimation (fig, plot, interval = 100, blit = True)
# ani.save ('sample2.gif', writer = 'imagemagick')
plt.show ()

% matplotlib inline
% matplotlib nbagg
Since I saw the description that is necessary when running on jupyter, I get an error.
Also, it is executed with vscode, but is this also affected?
It feels like # %% for each cell.

Append

It didn't work on the jupyter notebook, but when run in the terminal as a .py file
It went well.

  • Answer # 1

    Try deleting the argumentblit = True.

    from IPython.display import HTML
    from matplotlib import animation
    import matplotlib.pyplot as plt
    import random
    fig = plt.figure ()
    xlim = [0, 100]
    X, Y = [], []
    def plot (data):
        plt.cla () # delete previous graph
        Y.append (random.random ()) # create data
        X.append (len (Y))
        if len (X)>100: # update drawing range
            xlim [0] + = 1
            xlim [1] + = 1
        plt.plot (X, Y) # create next graph
        plt.title ("sample animation (real time)")
        plt.ylim (-1, 2)
        plt.xlim (xlim [0], xlim [1])
    # Create animation by calling plot function every 10ms
    ani = animation.FuncAnimation (fig, plot, interval = 100)
    # ani.save ('sample2.gif', writer = 'imagemagick')
    HTML (ani.to_jshtml ())

Related articles