使用散点图(matplotlib)为二维数组设置动画并改变颜色

Animating a 2D array with changing colors using scatter (matplotlib)

我想制作一个二维数组(带有固定点)的动画,其中点的颜色会发生变化。由于其他原因,我使用的是 class Individual,它具有 x 坐标、y 坐标和属性颜色。我的代码:

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

N = 100

class Individual:
    def __init__(self, x_axis, y_axis, color):
        self.x_axis = x_axis
        self.y_axis = y_axis
        self.color = color

population = np.empty([N], dtype=Individual)

i = 0
while i < 10:
    population[i] = Individual(np.random.uniform(0, 1), np.random.uniform(0, 1), "red")
    i = i + 1

i = 10
while i < N:
    population[i] = Individual(np.random.uniform(0, 1), np.random.uniform(0, 1), "blue")
    i = i + 1

fig, ax = plt.subplots()
scat = ax.scatter([i.x_axis for i in population], [i.y_axis for i in population], 
                  c=[i.color for i in population])
ax.set_xlim((0, 1))
ax.set_ylim((0, 1))
ax.grid(b=True, which='major', color='k', linestyle='--')

def init():
    scat = ax.scatter([i.x_axis for i in population], [i.y_axis for i in population], 
                      c=[i.state for i in population])
    return scat,

def animate(i):
    for i in population:   # only exemplary update
        if i.state == 'red':
            i.state = 'blue'
        else:
            i.state = 'red'
    c = [i.state for i in population]
    scat.set_array(c) # this is supposed to update the colors
    return scat,

anim = animation.FuncAnimation(scat, animate, init_func=init, frames=200, 
                               interval=20, blit=True)
plt.show()

我收到这些错误消息:

Traceback (most recent call last):
  File "C:/Users/benno/PycharmProjects/AnimationTests/Animation.py", line 50, in <module>
    anim = animation.FuncAnimation(scat, animate, init_func=init, frames=200, interval=20, blit=True)
  File "C:\Users\benno\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\animation.py", line 1696, in __init__
    TimedAnimation.__init__(self, fig, **kwargs)
  File "C:\Users\benno\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\animation.py", line 1433, in __init__
    event_source = fig.canvas.new_timer()
AttributeError: 'PathCollection' object has no attribute 'canvas'

我做错了什么根本性的事吗?

matplotlib.animation.FuncAnimation expects a matplotlib.figure.Figure instance as the first positional argument, not a matplotlib.artist。在您的代码中 scatartistfigFigure 实例。该行

anim = animation.FuncAnimation(scat, animate, init_func=init, frames=200, 
                               interval=20, blit=True)

应该是

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, 
                               interval=20, blit=True)