python - fork 流图的 Matplotlib 动画

标签 python animation matplotlib

我目前正在尝试制作典型鞍节点 fork 颂歌的动力学动画:dx/dt = r + x^2。 r 的特定值的快照是通过 r = -1 到 1 的streamplot 函数实现的。不幸的是,init 函数和animate 函数无法正常工作,因为.set_array 不适用于streamplots。我也不确定如何在动画函数的每次迭代中更新流。我的问题是我应该如何修改 animate 和 init 函数,以便 funcanimation 函数给出正确的动画流图。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation


nx, ny = .02, .02
x = np.arange(-15, 15, nx)
y = np.arange(-10, 10, ny)
X, Y = np.meshgrid(x, y)
dy = -1 + Y**2
dx = np.ones(dy.shape)

dyu = dy / np.sqrt(dy**2 + dx**2)
dxu = dx / np.sqrt(dy**2 + dx**2)


color = dyu
fig, ax = plt.subplots()
stream = ax.streamplot(X,Y,dxu, dyu, color=color, density=2, cmap='jet',arrowsize=1)
ax.set_xlabel('t')
ax.set_ylabel('x')

def init():
stream.set_array([])
return stream

def animate(iter):
    dy = -1 + iter * 0.01 + Y**2
    dx = np.ones(dy.shape)
    dyu = dy / np.sqrt(dy**2 + dx**2)
    dxu = dx / np.sqrt(dy**2 + dx**2)
    stream.set_array(dyu.ravel())

    return stream

anim =   animation.FuncAnimation(fig, animate, frames=100, interval=50, blit=False, repeat=False)
plt.show()

最佳答案

我通过清除每次迭代中的线条和箭头来解决这个问题:

ax.collections = [] # clear lines streamplot
ax.patches = [] # clear arrowheads streamplot

所以,我修改了你的代码:

#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation


nx, ny = .02, .02
x = np.arange(-15, 15, nx)
y = np.arange(-10, 10, ny)
X, Y = np.meshgrid(x, y)
dy = -1 + Y**2
dx = np.ones(dy.shape)

dyu = dy / np.sqrt(dy**2 + dx**2)
dxu = dx / np.sqrt(dy**2 + dx**2)

color = dyu
fig, ax = plt.subplots()
stream = ax.streamplot(X,Y,dxu, dyu, color=color, density=2, cmap='jet',arrowsize=1)
ax.set_xlabel('t')
ax.set_ylabel('x')

def animate(iter):
    ax.collections = [] # clear lines streamplot
    ax.patches = [] # clear arrowheads streamplot
    dy = -1 + iter * 0.01 + Y**2
    dx = np.ones(dy.shape)
    dyu = dy / np.sqrt(dy**2 + dx**2)
    dxu = dx / np.sqrt(dy**2 + dx**2)
    stream = ax.streamplot(X,Y,dxu, dyu, color=color, density=2, cmap='jet',arrowsize=1)
    print(iter)
    return stream

anim =   animation.FuncAnimation(fig, animate, frames=100, interval=50, blit=False, repeat=False)
anim.save('./animation.gif', writer='imagemagick', fps=60)
# plt.show()

animation

关于python - fork 流图的 Matplotlib 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013749/

相关文章:

python - 3D 动画中每个球体的随机方向

python - Pandas 绘制日期

python - Keras model.predict 函数给出输入形状错误

python 字典,用于在值小于输入时打印库存

objective-c - iOS 10 UILabels -> 1 UIView -> 使用动画循环

html - 将一个 css3 动画替换为另一个

python - 我可以使用 Augustus (Python) 应用包含 DefineFunction 的 PMML 模型吗?

python - 来自 Pandas 数据框的多个箱线图

python - 共享辅助轴

python - 共享 x 轴且数据不完整的 Pandas