使用matplotlib制作毫米波动画

Animation of millimeter wave using matplotlib

我正在尝试创建微波传播和传播时改变频率的模拟。 x 轴是时间,波应沿 x 轴移动,同时随后改变频率(从 3GHz 到 30GHz)。时间间隔是一纳秒,因为如果超过这个时间,它们就会太快而无法清楚地注意到运动。

我已经创建了 wave 的静态模型 matplotlib.pyplot。现在我想使用 matplotlib.animation 来制作动画。 我可以按照此 article 中的指南成功创建正弦波动画,但我不知道从那里去哪里。

如何利用 matplotlib.animation 绘制正弦波的示例代码并将其调整为动画微波?

微波炉型号:

用于绘制微​​波模型的代码:

import numpy as np
from scipy.signal import chirp
import matplotlib.pyplot as plt
plt.style.use('seaborn-pastel')

T = 0.000000001 #one nanosecond 
n = 1000 # number of samples to generate - the more generated,the more smooth the curve
t = np.linspace(0, T, n, endpoint=False) # x-axis 
f0_micro = 3000000000 #frequency min value: 3GHz
f1_micro = 30000000000 #frequency max value: 30GHz
y_micro = chirp(t, f0_micro, T, f1_micro, method='logarithmic')

plt.plot(t,y_micro)
plt.grid(alpha=0.25)
plt.xlabel('t (secs)')
plt.title('Microwaves in one nanosecond')
plt.show()

动画正弦波视频:

https://miro.medium.com/max/960/1*Aa4huCJefHt7nlX3nKQKGA.gif

用于绘制动画正弦波的代码:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')


fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)

def init():
    line.set_data([], [])
    return line,
def animate(i):
    x = np.linspace(0, 4, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)


anim.save('sine_wave.gif', writer='imagemagick')

对于此类动画

而不是绘制所有点

plt.plot(t, y_micro) # <--- skip it

您必须创建空图 - 具有正确的限制

fig = plt.figure()

ax = plt.axes(xlim=(t[0], t[-1]), ylim=(min(y_micro), max(y_micro)))

line, = ax.plot([], [], lw=3)

以后在animation中你可以使用i只放置部分点

line.set_data(t[:i], y_micro[:i])

import numpy as np
from scipy.signal import chirp
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')

# --- generate all data without drawing ---

T = 0.000000001 #one nanosecond 
n = 1000 # number of samples to generate - the more generated,the more smooth the curve

t = np.linspace(0, T, n, endpoint=False) # x-axis 

f0_micro = 3000000000 #frequency min value: 3GHz
f1_micro = 30000000000 #frequency max value: 30GHz
y_micro = chirp(t, f0_micro, T, f1_micro, method='logarithmic')

# --- create empty plot ---

#plt.plot(t,y_micro) # <--- skip it

fig = plt.figure()
ax = plt.axes(xlim=(t[0], t[-1]), ylim=(min(y_micro), max(y_micro)))
line, = ax.plot([], [], lw=3)

# --- other elements on plot ---

plt.grid(alpha=0.25)
plt.xlabel('t (secs)')
plt.title('Microwaves in one nanosecond')

# --- animate it ----

def init():
    # put empty data at start
    line.set_data([], [])
    return line,
    
def animate(i):
    # put new data in every frame using `i`
    line.set_data(t[:i], y_micro[:i])
    return line,

# calculate how many frames has animation
frames_number = len(t)

anim = FuncAnimation(fig, animate, init_func=init, frames=frames_number, interval=10, blit=True)

plt.show()

# I use `fps` (frames per second) to make it faster in file
anim.save('microwave.gif', fps=120) #, writer='imagemagick')

编辑

如果您需要带边距的绘图,那么您必须向限制添加一些值,因为现在绘图不会自动添加边距。

x_margin = T/30  # I tested manually different values
y_margin = 0.1   # I tested manually different values

x_limits = (t[0] - x_margin, t[-1] + x_margin)
y_limits = (min(y_micro) - y_margin, max(y_micro) + y_margin)

fig = plt.figure()
ax = plt.axes(xlim=x_limits, ylim=y_limits)
line, = ax.plot([], [], lw=3)

如果你想要文件中的动画更快,那么你可以尝试使用 save( ..., fps= ...) 来更改 frames per second.

的数量

或者你可以少画几帧

frames_number = len(t) // 2

并且每帧显示更多的点

i = i*2
line.set_data(t[:i], y_micro[:i])

赛璐珞是 matplotlib.animate 的一种更新且更易于使用的替代品。

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import chirp
from celluloid import Camera

fig = plt.figure()
camera = Camera(fig)

T = 0.000000001 #one nanosecond
n = 1000 # number of samples to generate - the more generated,the more smooth the curve
t = np.linspace(0, T, n, endpoint=False) # x-axis
f0_micro = 3000000000 #frequency min value: 3GHz
f1_micro = 30000000000 #frequency max value: 30GHz
y_micro = chirp(t, f0_micro, T, f1_micro, method='logarithmic')

for i in range(len(t)):

    plt.plot(t[:i], y_micro[:i], "r")
    camera.snap()

    plt.grid(alpha=0.25)
    plt.xlabel('t (secs)')
    plt.title('Microwaves in one nanosecond')

animation = camera.animate(interval=10)
plt.show()

它可以做你想做的事,只需对静态图的代码进行很少的修改。您不需要定义额外的功能等

最终结果是这样的