为什么 FuncAnimation 会回到原点?
Why does FuncAnimation revert back to the origin?
我正在尝试使用 FuncAnimation 为布朗运动的示例路径制作动画,但动画一直在恢复原点。
这是我的代码。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# create the time interval and partition
t = 2.5
n = 100
# How many sample paths?
path_amt = 2
# Create a brownian sample path
def bsp(t, n):
dB = np.sqrt(t / n) * np.random.normal(0, 1, size=n)
B = np.zeros(n+1)
B[1:] = np.cumsum(dB)
return(B)
# Simulate "path_amt" sample paths
def sample_paths(i, t ,n):
BSP = np.zeros((i, n+1))
for k in range(i):
BSP[k,:] = bsp(t, n)
return(BSP)
B_paths = sample_paths(path_amt, t, n)
这部分基本上只是提出了两个独立的 Browinan 动议。每个布朗运动都是一个长度为 n+1 的一维数组。然后,我将两个布朗运动存储在标题为 B_paths 的 (2, n+1) 数组中,因此每一行代表一个布朗运动。这是动画的代码。
# Create the animation function for the sample path
x = []
y = []
t_axis = np.linspace(0, t, n+1)
fig, ax = plt.subplots()
ax.set_xlim(0, 3)
ax.set_ylim(-4, 4)
line, = ax.plot(0, 0)
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
return line,
animation = FuncAnimation(fig, func = anim_func, \
frames = np.linspace(0, t, n+1), interval = 10)
plt.show()
因为动画在循环播放。一旦帧到达 t=2.5
,它就会重新开始,但是在你的 anim_func
中你没有清除 x, y
。
您可以修改此功能:
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
if i == t:
x.clear()
y.clear()
return line,
或在 FuncAnimation
调用中设置 repeat=False
。
我正在尝试使用 FuncAnimation 为布朗运动的示例路径制作动画,但动画一直在恢复原点。
这是我的代码。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# create the time interval and partition
t = 2.5
n = 100
# How many sample paths?
path_amt = 2
# Create a brownian sample path
def bsp(t, n):
dB = np.sqrt(t / n) * np.random.normal(0, 1, size=n)
B = np.zeros(n+1)
B[1:] = np.cumsum(dB)
return(B)
# Simulate "path_amt" sample paths
def sample_paths(i, t ,n):
BSP = np.zeros((i, n+1))
for k in range(i):
BSP[k,:] = bsp(t, n)
return(BSP)
B_paths = sample_paths(path_amt, t, n)
这部分基本上只是提出了两个独立的 Browinan 动议。每个布朗运动都是一个长度为 n+1 的一维数组。然后,我将两个布朗运动存储在标题为 B_paths 的 (2, n+1) 数组中,因此每一行代表一个布朗运动。这是动画的代码。
# Create the animation function for the sample path
x = []
y = []
t_axis = np.linspace(0, t, n+1)
fig, ax = plt.subplots()
ax.set_xlim(0, 3)
ax.set_ylim(-4, 4)
line, = ax.plot(0, 0)
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
return line,
animation = FuncAnimation(fig, func = anim_func, \
frames = np.linspace(0, t, n+1), interval = 10)
plt.show()
因为动画在循环播放。一旦帧到达 t=2.5
,它就会重新开始,但是在你的 anim_func
中你没有清除 x, y
。
您可以修改此功能:
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
if i == t:
x.clear()
y.clear()
return line,
或在 FuncAnimation
调用中设置 repeat=False
。