Reputation: 159
I'm trying to create a simulation of microwaves travelling and changing frequencies as they travel. The x-axis is time, and the wave should move along the x-axis while subsequently changing frequencies (from 3GHz to 30GHz). The time interval is one nanosecond because higher than that they would be too fast to clearly notice the movement.
I have already created a static model of the wave matplotlib.pyplot. Now I want to use matplotlib.animation to animate it. I could successfully create an animation of a sine wave by following the guide in this article, but I don't know where to go from there.
How can I utilize the matplotlib.animation example code of drawing a sine wave and tweak it to be an animated microwave?
Model of the microwave:
Code used in plotting microwave model:
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()
Video of animated sine wave:
https://miro.medium.com/max/960/1*Aa4huCJefHt7nlX3nKQKGA.gif
Code used in plotting animated sine wave:
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')
Upvotes: 0
Views: 328
Reputation: 3272
A newer and slightly more easier to use alternative to matplotlib.animate
is celluloid.
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()
It can do what you want to do with very little modifications to the code for a static plot. You don't need to define extra functions etc.
The final result looks like this
Upvotes: 2
Reputation: 142651
For this type of animation
Instead of drawing all points
plt.plot(t, y_micro) # <--- skip it
you have to create empty plot - with correct limits
fig = plt.figure()
ax = plt.axes(xlim=(t[0], t[-1]), ylim=(min(y_micro), max(y_micro)))
line, = ax.plot([], [], lw=3)
and later in animation
you can use i
to put only part of points
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')
EDIT
If you need plot with margins then you have to add some values to limits because now plot doesn't add margins automatically.
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)
If you want faster animation in file then you may try to use save( ..., fps= ...)
to chage number of frames per second
.
Or you can draw less frames
frames_number = len(t) // 2
and display more points in every frame
i = i*2
line.set_data(t[:i], y_micro[:i])
Upvotes: 2