Вопрос об изменении маркера разброса при анимации - PullRequest
1 голос
/ 25 сентября 2019

У меня проблема с изменением направления "треугольного маркера" при разбросе во время анимации перемещения точек.Таким образом, у меня есть 100 точек, которые перемещаются случайным образом по области, и на каждой итерации они могут изменять направление движения (каждая точка отдельно от другой / они независимы).Я читаю из каждой точки в каждой итерации каждую точку с указанием направления и хочу построить ее.То, что каждые 10 ходов очков изменяются другими поколениями очков, которые все еще движутся случайным образом.Мой код вроде работает, но не так, как должен.Направление каждой точки задается в начале каждого поколения, но не меняется после каждой итерации.Может ли кто-нибудь помочь мне изменить это?;)

def update(i, data, agent, texts, NUMBER_OF_POINTS): 

    x_N, y_N = [], []
    x_S, y_S = [], []
    x_W, y_W = [], []
    x_E, y_E = [], []
    for point, coordinate in IT.islice(data, NUMBER_OF_POINTS):
        if point in range(100):
            if coordinate[1] == Direction.N:
                texti = texts[point]
                x, y = coordinate[0].cpu().numpy()
                x_N.append(x)
                y_N.append(y)
                texti.set_position((x, y))
                agent_N.set_offsets(np.column_stack([x_N, y_N]))
                agent_N.set_paths([MarkerStyle("^").get_path().transformed(MarkerStyle("^").get_transform())])
            elif coordinate[1] == Direction.S:
                texti = texts[point]
                x, y = coordinate[0].cpu().numpy()
                x_S.append(x)
                y_S.append(y)
                texti.set_position((x, y))
                agent_S.set_offsets(np.column_stack([x_S, y_S]))
                agent_S.set_paths([MarkerStyle("v").get_path().transformed(MarkerStyle("v").get_transform())])
            elif coordinate[1] == Direction.W:
                texti = texts[point]
                x, y = coordinate[0].cpu().numpy()
                x_W.append(x)
                y_W.append(y)
                texti.set_position((x, y))
                agent_W.set_offsets(np.column_stack([x_W, y_W]))
                agent_W.set_paths([MarkerStyle("<").get_path().transformed(MarkerStyle("<").get_transform())])
             else:
                texti = texts[point]
                x, y = coordinate[0].cpu().numpy()
                x_E.append(x)
                y_E.append(y)
                texti.set_position((x, y))
                agent_E.set_offsets(np.column_stack([x_E, y_E]))
     return [agent_N, agent_S, agent_W, agent_E] + texts

if __name__ == "__main__":
    matplotlib.animation.Animation._blit_draw = _blit_draw
    num_frames = NUMBER_OF_GENERATIONS*SINGLE_LIFETIME
    fig, ax = plt.subplots()
    agent_N = ax.scatter([0] * NUMBER_OF_POINTS, [0] * NUMBER_OF_POINTS, c="lightblue", s=100)
    agent_S = ax.scatter([0] * NUMBER_OF_POINTS, [0] * NUMBER_OF_POINTS, c="lightblue", s=100)
    agent_E = ax.scatter([0] * NUMBER_OF_POINTS, [0] * NUMBER_OF_POINTS, c="lightblue", s=100)
    agent_W = ax.scatter([0] * NUMBER_OF_POINTS, [0] * NUMBER_OF_POINTS, c="lightblue", s=100)
    texts = []
    for i in range(NUMBER_OF_AGENTS):
        t = ax.text(0, 0, str(i), fontsize=10, animated=True)
        texts.append(t)
    path = "output.txt"
    data = get_data(path)
    ani = FuncAnimation(fig, update, range(1, num_frames + 1), init_func=init, blit=True, fargs=(data, agent_N, agent_S, agent_W, agent_E, mushroom, toadstool, texts, title, NUMBER_OF_POINTS), interval=1000, repeat=False,)
    plt.grid(True)
    plt.show()

1 Ответ

1 голос
/ 25 сентября 2019

Суть моего комментария в том, что почти невозможно сказать вам, что не так с вашим кодом, когда мы не можем запустить ваш код.

В любом случае, вотпростая анимация, где маркеры меняются в зависимости от направления движения, возможно, это поможет вам разобраться.Если нет, то рассмотрите возможность предоставления фактического MVCE

np.random.seed(12345)
N_points = 20
N_frames_per_direction = 20

O_path = MarkerStyle('o').get_path().transformed(MarkerStyle('o').get_transform())
N_path = MarkerStyle('^').get_path().transformed(MarkerStyle('^').get_transform())
S_path = MarkerStyle('v').get_path().transformed(MarkerStyle('v').get_transform())
E_path = MarkerStyle('>').get_path().transformed(MarkerStyle('>').get_transform())
W_path = MarkerStyle('<').get_path().transformed(MarkerStyle('<').get_transform())

x_init,y_init = 20*np.random.random(size=(2,N_points)) # initial position
dxes = np.concatenate([np.random.normal(loc=1, scale=1, size=(N_points,N_frames_per_direction)), 
                       np.zeros(shape=(N_points, N_frames_per_direction)),
                       np.random.normal(loc=-1, scale=1, size=(N_points, N_frames_per_direction)),
                       np.zeros(shape=(N_points, N_frames_per_direction))], axis=1)
dyes = np.concatenate([np.zeros(shape=(N_points, N_frames_per_direction)),
                       np.random.normal(loc=-1, scale=1, size=(N_points, N_frames_per_direction)),
                       np.zeros(shape=(N_points, N_frames_per_direction)),
                       np.random.normal(loc=1, scale=1, size=(N_points,N_frames_per_direction)),], axis=1)



fig, ax = plt.subplots()
sc = ax.scatter([],[], marker='o')
ax.set_xlim(-10,50)
ax.set_ylim(-25,25)

def init():
    sc.set_offsets(np.c_[x_init,y_init])
    return sc,

def animate(i):
    x,y = sc.get_offsets().T
    x += dxes[:,i]
    y += dyes[:,i]
    sc.set_offsets(np.c_[x,y])
    sc.set_paths([E_path if dx>0 
                  else W_path if dx<0 
                  else N_path if dy>0 
                  else S_path if dy<0 
                  else O_path for dx,dy in zip(dxes[:,i], dyes[:,i])])
    return sc,

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=4*N_frames_per_direction, blit=True)
plt.show()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...