Search code examples
pythonmatplotlibanimationmathpycharm

The animation function must return a sequence of Artist objects


I am trying to test a Matplotlib animation example on my Pycharm which is listed as following:

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

n = 1000
def update(curr):
    if curr == n:
        a.event_source.stop()

    subplot1.cla()
    subplot2.cla()
    subplot3.cla()
    subplot4.cla()

    # subplots re-set to standard positions
    x1 = np.random.normal(0, 1, n)
    x2 = np.random.gamma(2, 1, n)
    x3 = np.random.exponential(2, n)
    x4 = np.random.uniform(0, 6, n)

    # increment the number of bins in every 10th frame
    # bins = 20 + curr // 10
    bins = 10 + curr

    # drawing the subplots
    subplot1.hist(x1, bins=bins, alpha=0.5, color='red')
    subplot2.hist(x2, bins=bins, alpha=0.5, color='green')
    subplot3.hist(x3, bins=bins, alpha=0.5, color='blue')
    subplot4.hist(x4, bins=bins, alpha=0.5, color='darkorange')

    # set all ticks to null
    subplot1.set_xticks([])
    subplot2.set_xticks([])
    subplot3.set_xticks([])
    subplot4.set_xticks([])
    subplot1.set_yticks([])
    subplot2.set_yticks([])
    subplot3.set_yticks([])
    subplot4.set_yticks([])

    # name the subplots
    subplot1.set_title('Normal')
    subplot2.set_title('Gamma')
    subplot3.set_title('Exponential')
    subplot4.set_title('Uniform')

    # the title will change to reflect the number of bins
    fig.suptitle('No of bins: {}'.format(bins))

    # no redundant space left for saving into mp4
    plt.tight_layout()

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Kuba Siekierzynski', title='Distributions'), bitrate=1800)

fig, ([subplot1, subplot2], [subplot3, subplot4]) = plt.subplots(2, 2)
a = animation.FuncAnimation(fig, update, interval=100, save_count=500, blit=True, frames=100)

# will only work with ffmpeg installed!!!
a.save('distributions.mp4', writer=writer)
plt.show()

the terminal shows the error:

raise RuntimeError('The animation function must return a '
RuntimeError: The animation function must return a sequence of Artist objects.

I have try to several time but cannot figure it out


Solution

  • As explained here for the case of init_func, since you are setting the parameter blit = True in the FuncAnimation definition, your update function has to return the plotting object. As an alternative, you can set blit = False; in that case, you get this animation:

    enter image description here