MyTivoli
MyTivoli

Reputation: 125

plot numpy fft in python returns wrong plot

I am trying to use numpy fft to plot some data from a dataframe :

plt.plot(np.fft.fft(df_valid_daily_activity.stepsDaily))

I get this : enter image description here

I don't understand why the plot is so steep in the beginning and then seems to stabilise? Also I get this warning :

Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)

example of the data I am trying to plot :

2      12693.0
3      18387.0
4      18360.0
5      11684.0
6      12722.0
        ...   
273    27836.0
274    15566.0
280     7836.0
281    17787.0
284     7739.0
Name: stepsDaily, Length: 199, dtype: float64 

Any ideas why ? Thanks!

Edit: tried subtracting mean - still looks weird enter image description here

Upvotes: 0

Views: 1645

Answers (2)

Silent
Silent

Reputation: 99

I guess you should try it with logscales plots. At first, I suggest using numpy.fft.fftshift to Shift the zero-frequency component to the center of the spectrum.

import random
import matplotlib.pyplot as plt
import numpy as np
f = [random.randint(5000, 20000) for i in range(300)]
ff = np.fft.fftshift(f)

Then you can plot them in 'semilogx', 'semilogy', and 'loglog' scale.

Semi Log X: Semi Log X Semi Log Y: Semi Log Y Log Scale Both: Log Scale Both

Upvotes: 1

David Hoffman
David Hoffman

Reputation: 2343

The function you’re using is a full complex Fourier transform: when applied to real data it will be symmetrical about zero. Two things you could do: use np.fft.fftshift to shift the data such that the zero frequency is in the middle (or use np.fft.fftfreq to calculate the frequencies) or use np.fft.rfft which is a transform for real data and will return half the full FFT.

It would be good to know your intended use of the FFT. Most people (myself included) are really only interested in what frequencies are present in the data. For that a plot of the magnitude squared (usually on a logarithmic scale) of the FFT can be used.

Upvotes: 1

Related Questions