[PYTHON] Time change visualization (spectrogram) of frequency analysis (FFT) with scipy

With the function from scipy0.16, it has become possible to easily write the visualization of the time change of the acquired signal by applying FFT. It is possible to do something like voice analysis with arbitrary data. In my Mac environment, I put python in anaconda and the version of scipy was old, so

conda update scipy

And made Scipy new. Use scipy's fftpack if you don't want to keep track of time.

python usage environment

I built it with anaconda, python2.7, scipy0.16, Mac OSX

Transient frequency analysis

The FFT function of scipy.fftpack can visualize the signal of a stationary signal, but it is difficult to visualize the frequency change of a non-stationary signal in the time direction. The spectrogram of scipy.signal can be used to visualize the time change of the FFT result.

For example, try using your own data. Here, in the same directory as the script called fft.py, I put a CSV file called data.CSV with the time in the first column and the data in the second column. The data was acquired at 10kHz.

code

fft.py


# -*- coding: utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy import signal

plt.close('all')

input_file = u"data.CSV"
(time, data) = np.loadtxt(input_file,unpack=True, delimiter=",",usecols = (0,1))

fs = 10000.0 #Sampling frequency
f,t,Sxx = signal.spectrogram(data, fs, nperseg=512)

plt.figure()
plt.pcolormesh(t,f,Sxx,vmax=1e-6)
plt.xlim([0,18])
plt.xlabel(u"time[sec]")
plt.ylabel(u"frequency[Hz]")
# plt.colorbar()
plt.show()

The nperseg of signal.spectrogram is the number of frequency divisions. If you change this, the number of divisions will change. Default 256. The color map may be difficult to see depending on how the frequencies are set, so it is advisable to specify the vmax / vmin value of pcolormesh of matplolib.

spectram.png

reference

http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.signal.spectrogram.html#scipy.signal.spectrogram

http://docs.scipy.org/doc/scipy/reference/fftpack.html

Recommended Posts

Time change visualization (spectrogram) of frequency analysis (FFT) with scipy
Time series analysis 3 Preprocessing of time series data
Data analysis starting with python (data visualization 1)
Data analysis starting with python (data visualization 2)
Time series analysis 4 Construction of SARIMA model
Sentiment analysis of tweets with deep learning
Recommendation of Altair! Data visualization with Python