gpt4 book ai didi

python - 向随机游走图添加动画 [Python]

转载 作者:行者123 更新时间:2023-12-01 01:47:44 26 4
gpt4 key购买 nike

我写了一个绘制随机游走的代码。有traj生成不同的随机游走,每个随机游走由 n 组成脚步。我想为他们的 Action 制作动画。我怎样才能做到这一点?
我的代码如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def random_walk_2D(n, traj = 1):

for i in range(traj):

skoki = np.array([[0, 1], [1, 0], [-1, 0], [0, -1]])
losy = np.random.randint(4, size = n)

temp = skoki[losy, :]

x = np.array([[0, 0]])

temp1 = np.concatenate((x, temp), axis = 0)

traj = np.cumsum(temp1, axis = 0)

plt.plot(traj[:, 0], traj[:, 1])
plt.plot(traj[-1][0], traj[-1][1], 'ro') #the last point

plt.show()

最佳答案

就目前而言,您可以一次性生成 traj。我的意思是 trajtraj = np.cumsum(temp1, axis = 0)已经包含了从头到尾的所有“故事”。如果你想创建一个“实时”的动画,你不应该生成traj一次,但迭代地,绘制新的步骤。怎么办:

import numpy as np
import matplotlib.pyplot as plt

def real_time_random_walk_2D_NT(
nb_steps, nb_trajs, with_dots=False, save_trajs=False, tpause=.01
):
"""
Parameters
----------
nb_steps : integer
number of steps
nb_trajs : integer
number of trajectories
save_trajs : boolean (optional)
If True, entire trajectories are saved rather than
saving only the last steps needed for plotting.
False by default.
with_dots : boolean (optional)
If True, dots representative of random-walking entities
are displayed. Has precedence over `save_trajs`.
False by default.
tpause : float (optional)
Pausing time between 2 steps. .01 secondes by default.
"""
skoki = np.array([[0, 1], [1, 0], [-1, 0], [0, -1]])
trajs = np.zeros((nb_trajs, 1, 2))
for i in range(nb_steps):
_steps = []
for j in range(nb_trajs):
traj = trajs[j,:,:]
losy = np.random.randint(4, size = 1)
temp = skoki[losy, :]
traj = np.concatenate((traj, temp), axis = 0)
traj[-1,:] += traj[-2,:]
_steps.append(traj)
if save_trajs or with_dots:
trajs = np.array(_steps)
if with_dots:
plt.cla()
plt.plot(trajs[:,i, 0].T, trajs[:,i, 1].T, 'ro') ## There are leeway in avoiding these costly transpositions
plt.plot(trajs[:,:i+1, 0].T, trajs[:,:i+1, 1].T)
else:
plt.plot(trajs[:,-1+i:i+1, 0].T, trajs[:,-1+i:i+1, 1].T)
else:
trajs = np.array(_steps)[:,-2:,:]
plt.plot(trajs[:,:, 0].T, trajs[:,:, 1].T)

plt.pause(tpause)


real_time_random_walk_2D_NT(50, 6, with_dots=True)

enter image description here
real_time_random_walk_2D_NT(50, 6)

enter image description here

关于python - 向随机游走图添加动画 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47445394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com