使用散点图(matplotlib)对2D数组进行动画处理以改变颜色

时间:2020-04-09 23:40:21

标签: python matplotlib animation scatter-plot

我想为2D数组(具有固定点)设置动画,点的颜色会改变。出于其他原因,我正在使用具有x坐标,y坐标和属性颜色的Personal类。我的代码:

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'

我从根本上做错了什么吗?

1 个答案:

答案 0 :(得分:0)

matplotlib.animation.FuncAnimation需要一个matplotlib.figure.Figure实例作为第一个位置参数,而不是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)