Анимация 2D-массива с изменением цвета с помощью scatter (matplotlib) - PullRequest
0 голосов
/ 10 апреля 2020

Я хочу анимировать 2D-массив (с фиксированными точками), где цвет точек меняется. По другим причинам я использую класс 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'

Я сделал что-то в корне неправильно?

1 Ответ

0 голосов
/ 10 апреля 2020

matplotlib.animation.FuncAnimation ожидает экземпляр matplotlib.figure.Figure в качестве первого позиционного аргумента, а не matplotlib.artist. В вашем коде scat - это artist, fig - это Figure экземпляр. Линия

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)
...