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

标签 python numpy animation matplotlib random

我写了一个绘制随机游走的代码。有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/

相关文章:

python - 在 python 中使用 eval() 添加数字

python - Pygame 错误未显示缩放图像

python - 卷积中的每第 N 个元素

python - 添加不同维度的矩阵

java - Jbutton 在两种背景颜色之间闪烁

python - 如何从 BeautifulSoup 中的表 td 中获取值?

python - NumPy 中 random.choice 的多维数组

python - Pandas/Numpy 中的迭代公式

python - 那么为什么这个 Pygame move 代码可以工作,而这个却不行呢?

iphone - 进入后台后动画使应用程序崩溃