分叉流图的Matplotlib动画

2024-10-16 17:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试动画一个典型的鞍结分叉模式:dx/dt=r+x^2。在r的特定值下的快照是通过从r=-1到1的streamplot函数实现的。不幸的是,init函数和animate函数不能正常工作,因为.set_数组不适用于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()

Tags: 函数importstreaminitasnppltsqrt
1条回答
网友
1楼 · 发布于 2024-10-16 17:15:38

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

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

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

^{pr2}$

animation

相关问题 更多 >