gpt4 book ai didi

python - 使用 matplotlib 动画波脉冲

转载 作者:行者123 更新时间:2023-12-04 14:05:08 24 4
gpt4 key购买 nike

我正在尝试在 Jupyter Lab 中使用 matplotlib 为高斯调制波脉冲制作动画,但我无法让它工作。我希望脉冲及时向前移动,即从中间向右移动(换句话说,显示脉冲传播)。

我使用 scipy 的“signal.gausspulse”函数创建脉冲本身,该函数创建脉冲的静态图像。然后,我创建了一个 meshgrid 并尝试将脉冲“映射”到它上面,同时通过将帧编号“i”作为输入的动画函数对其进行循环,并循环遍历我们想要设置动画的值。

在我得到动画中的脉动之前,它只是静止的,没有任何运动。我认为这是因为带有波脉冲 y 值的整个数组没有随时间变化,所以我尝试创建一个循环来更新它。这有帮助,但它非常慢并且使脉搏向上移动两次,然后完全停止运动。

我无法弄清楚,真的不知道该怎么做,所以非常感谢任何帮助! :) 我可能误用了一些术语,所以我提前为此道歉 - 我试着评论代码并解释我经历的步骤,希望它能有所帮助。

%matplotlib widget

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

#setting up the canvas
fig, ax = plt.subplots(figsize=(5, 3))
ax.set(xlim=(-3, 3), ylim=(-1, 1))

#creating meshgrid for future animation
x = np.linspace(-10, 5, 200)
t = np.linspace(-10, 5, 200)
X2, T2 = np.meshgrid(x, t) #X2 and T2 are numpy arrays now

#creating the gaussian modulated pulse: fc is frequency and bw is another parameter than can be ignored
F = signal.gausspulse(X2, fc=5, bw = 0.3, retquad=False, retenv=True)[0]

#updating the values in F array to make the wave pulse move in time
j = 0
i = 0

for i in range(len(t)):
for j in range(len(t)):
F[i,j] += i - 5e-40 #some arbitrary value added/subtracted, chose e-40 bec of values in array F
#F[i,j] += j + 5e-40

#creting a Line.2D to be plotted later; F vs time

line = ax.plot(t, F[0, :], color='k', lw=2)[0]

#animating function
def animate(i):
return line.set_ydata(F[i,:])

anim = FuncAnimation(fig, animate, interval=1000, frames=1000, repeat = False)

plt.draw()
plt.grid(True)
plt.show()

enter image description here

最佳答案

您可以定义一个固定的 x_fixed 轴来绘制数据。然后计算一个新轴 x,通过在每次迭代中减去 i/10,它在每次迭代中向右平移。这个值是任意的,它决定了向右移动的速度。然后您计算平移轴上的新信号,但是您绘制相对于固定轴的信号。
使用 ax.cla() 清理之前的绘图并在每次迭代时设置网格和轴限制非常重要。
不需要网格或 for 循环。

完整代码

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


x_fixed = np.linspace(-3, 3, 200)


def animate(i):
ax.cla()

x = np.linspace(-3, 3, 200) - i/10
F = signal.gausspulse(x, fc = 5, bw = 0.3, retquad = False, retenv = True)[0]

ax.plot(x_fixed, F)

ax.set(xlim = (-3, 3), ylim = (-1, 1))
ax.grid()


fig, ax = plt.subplots(figsize=(5, 3))

anim = FuncAnimation(fig, animate, interval=1000, frames=1000, repeat = False)

plt.show()

enter image description here

关于python - 使用 matplotlib 动画波脉冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68806579/

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