gpt4 book ai didi

python - fork 流图的 Matplotlib 动画

转载 作者:太空宇宙 更新时间:2023-11-03 14:19:49 25 4
gpt4 key购买 nike

我目前正在尝试制作典型鞍节点 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com