Plotting the result of a Fourier transform using Matplotlib's Pyplot

Visualization is an important tool for understanding a lot of data. Here is an example.



>>> import numpy as np
>>> import matplotlib.pyplot as plt

>>> N = 256
>>> t = np.arange(N)

>>> m = 4
>>> nu = float(m)/N
>>> f = np.sin(2*np.pi*nu*t)
>>> ft = np.fft.fft(f)
>>> freq = np.fft.fftfreq(N)
>>> plt.plot(freq, ft.real**2 + ft.imag**2)
>>> plt.show()

Here is an explanation of the new commands in the code.

>>> import matplotlib.pyplot as plt

This command loads the Pyplot component of the Matplotlib package. You will use this package to create plots.



>>> m = 4
>>> nu = float(m)/N

Here we choose one of the discrete pure frequencies for our signal, namely for $m = 4$ as described above.



>>> freq = np.fft.fftfreq(N)

The fftfreq function generates a list of “frequencies”, corresponding to the components of the Fourier transform. It gives $N$ values in the interval (-0.5,0.5). To convert to the actual frequency, you need to divide by $\Delta t$, the sampling interval in time.



>>> plt.plot(freq, ft.real**2 + ft.imag**2)
>>> plt.show()

The first command creates the plot. In this plot the x axis is frequency and the y axis is the squared norm of the Fourier transform. Note that both arguments are vectors. Numpy does the calculation of the squared norm component by component. The second command displays the plot on your screen.