Matplotlib动画的分叉Streamplot

时间:2017-12-28 20:08:09

标签: python animation matplotlib

我目前正在尝试为典型的马鞍节点分叉ode的动力学设置动画:dx / dt = r + x ^ 2。使用r = -1到1的streamplot函数实现特定r值的快照。遗憾的是,init函数和animate函数无法正常工作,因为.set_array不适用于streamplots。我也不确定如何在animate函数中的每次迭代中更新流。我的问题是我应该如何修改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()

1 个答案:

答案 0 :(得分:0)

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

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