Frequency Spectrum

Analyze the strength of each frequency in a signal segment.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from scipy.fftpack import fft,ifft
#dt = tr.stats.npts/tr.stats.sampling_rate # 数据时间长度
df = tr.stats.sampling_rate
def FFT (Fs,data):
data = data - np.mean(data)
L = len(data) # 信号长度
N = int(np.power(2,np.ceil(np.log2(L)))) # 下一个最近二次幂
FFT_y = (abs(fft(data,N)))/L*2 # N点FFT,但除以实际信号长度 L
Fre = np.arange(int(N/2))*Fs/N # 频率坐标
FFT_y = FFT_y[range(int(N/2))] # 取一半
return Fre, FFT_y
#Fre, FFT_y1 = FFT(df, count)
Fre, FFT_y1 = FFT(df, tr.data)
plt.figure(figsize=(8,2),dpi=100)
plt.plot(Fre,FFT_y1)
#plt.plot(1/Fre/3600/24,FFT_y1)
plt.grid()
#plt.xlabel('Period (day)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power')
plt.xscale('log')
#plt.xlim(0,0.00002)
plt.show()

Output

spectrum

Time-Frequency Spectrum

Frequency spectrum at different time of the segment.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from scipy.signal import stft
df = tr.stats.sampling_rate
f, t, zxx = stft(tr.data, fs=df, nperseg=512, noverlap=512*0.9, nfft=512)
plt.figure(figsize=(10,10))
plt.imshow(np.abs(zxx), aspect='auto',
extent = (min(t), max(t), max(f), min(f))
)
plt.gca().invert_yaxis()
#cb = plt.colorbar()
#cb.ax.tick_params(labelsize = 20)
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.title('STFT Magnitude', size = 30)
plt.xlabel('Time [sec]', size = 30)
plt.ylabel('Frequency [Hz]', size = 30)

Output

Time-frequency-spectrum