2

I used fft.fft(data) and plotted that result I was expecting to the frequency that I gave in data. I was expecting to see 50 hz but I got something strange.

import numpy as np
import math as m
import matplotlib.pyplot as plt


data=[]

for x in range(1000):
    data.append(m.sin(2*m.pi*50*0.001*x))


plt.plot(np.fft.fft(data)/len(data))

plt.show()

What should I do to see 50 Hz as result?

Thank you very much

1
  • 1
    fyi, you can make data without that loop by using np.sin(2*np.pi*50*np.linspace(0,1,1000) Commented Apr 10, 2014 at 14:48

2 Answers 2

4

You need to specify the x axis in your plot.

First, create the data:

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 1, 1000)
data = np.sin(2*np.pi*50*t)

Now, get the frequencies:

f = np.fft.fftfreq(len(data), t[1]-t[0]) # length of data, and dt

And plot the magnitude of the fft vs frequencies:

data_fft = np.abs(np.fft.fft(data)) / len(data)
plt.plot(f, data_fft)

fft

Sign up to request clarification or add additional context in comments.

1 Comment

+1: I'm sure you know, but it's probably also a good idea to plot the magnitude, especially since the imaginary component is much larger than the real in this situation.
0

This is really a question for the DSP stack exchange (https://dsp.stackexchange.com/).

You are doing two things that are causing the odd result:

  1. You are performing a complex to complex FFT on real data, so you will have your signal mirrored about the Nyquist frequency (Hermitian symmetry).

  2. You are dividing and plotting the complex output, not the Fourier amplitudes or powers.(Matplotlib doesn't "get" complex numbers, so this comes out looking like garbage.)

try this instead:

plt.plot(abs(np.fft.rfft(data))/(len(data)/2))

2 Comments

Thank you so much for quick replies I appreciate all answers but I tried plt.plot(abs(np.fft.rfft(data))/len(data)) as ebarr's solution. There is one question about that. Amplitude is 0.5 in graph I was expecting 1 ???
if you use rfft then you must multiply by 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.