Home > database >  How to center the FFT of sine wave in matplotlib?
How to center the FFT of sine wave in matplotlib?

Time:02-06

I want to plot the FFT of a sine wave using matplotlib and I want to plot a single line at a frequency where the sine wave belongs.

here's my code

import numpy as np
import matplotlib.pyplot as plt


f = 3
t = np.arange(-np.pi, np.pi, 0.01)
y = np.sin(2*np.pi*f*t)


plt.subplot(2, 1, 1)
plt.plot(t, y)


ft = np.fft.fft(y)

plt.subplot(2, 1, 2)
plt.plot(ft.real)

plt.show()

And, here's the output of the above code.

FFT

I want to plot the FFT as a single line, and this single line will be straight up at the given sine wave's frequency. Suppose, if I have two sine waves of 20Hz and 40Hz added together like sine(2*pi*20*t) sine(2*pi*40*t) then their FFT should have two straight lines at 20Hz and 30Hz.

How do I fix my code to get what I wanted? I've seen many questions here on StackOverflow but I did not understand them. Any help would be appreciated.

CodePudding user response:

There are a few things to unpack here.

Use np.fft.rfft for real signals

Since your signal is real-valued (i.e. no complex numbers) there is no information contained in the second half of your fft. You should use the rfft in stead for real signals.

See The result

  •  Tags:  
  • Related