问题
The following python program plots a sinusoid:
import matplotlib.pyplot as plt
import numpy as np
# Canvas
plt.style.use("ggplot")
# Frequency, Oscillations & Range
f = int(input("Enter frequency: "))
n_o = int(input("Enter number of oscillations: "))
t_max = n_o/f
t = np.linspace(0, t_max, 1000)
# Sine
y_sin = np.sin(2*np.pi*f*t)
# Setting subplots on separate axes
fig, axs = plt.subplots(2, 1, constrained_layout = True)
# Sine axis
axs[0].plot(t, y_sin, color = "firebrick", label = "sin({}Hz)".format(f))
axs[0].axhline(y = 0, color = "grey", linestyle = "dashed", label = "y = 0")
axs[0].legend(loc = "lower left", frameon = True, fancybox = True,
shadow = True, facecolor = "white")
# Title
axs[0].set_title("Sine")
axs[0].set_xlabel("Time(s)")
axs[0].set_ylabel("Amplitude")
# Axis Limits
axs[0].axis([-0.05*t_max, t_max+0.05*t_max, -1.5, 1.5])
plt.show()
How can i plot the Fourier transform of this frequency in the second subplot? I have seen various examples but they only work with small frequencies, whereas i'm working with frequencies above 100 Hz. Thanks.
回答1:
By correctly applying FFT on your signal you should be just fine:
# FFT
# number of samples
N = len(t)
# time step
dt = t[1]-t[0]
# max number of harmonic to display
H_max = 5
xf = np.linspace(0.0, 1.0/(2.0*dt), N//2)
yf = np.fft.fft(y_sin)
axs[1].plot(xf, (2/N)*np.abs(yf[:N//2]))
axs[1].set_xlim([0, H_max*f])
axs[1].set_xlabel('f (Hz)')
axs[1].set_ylabel('$||H_i||_2$')
which gives for inputs f=100
and n_o=3
:
Hope this helps.
来源:https://stackoverflow.com/questions/61592545/plotting-fourier-transform-of-a-sinusoid-in-python