numpy - Plotting a fast Fourier transform in Python

Numpy - Plotting a fast Fourier transform in Python

To plot a Fast Fourier Transform (FFT) using NumPy and Matplotlib in Python, you can follow these steps. FFT is used to analyze the frequency components of a signal or a time series.

Step-by-Step Guide to Plotting FFT

1. Generate or Load Data

First, you need some data to analyze. For demonstration, let's generate a simple signal:

import numpy as np import matplotlib.pyplot as plt # Generate some data (sine wave) fs = 1000 # Sampling frequency t = np.linspace(0, 1, fs, endpoint=False) # Time vector from 0 to 1 second f = 5 # Frequency of the signal signal = np.sin(2 * np.pi * f * t) # Sine wave signal 

2. Perform FFT using NumPy

Next, compute the FFT of the signal using np.fft.fft() function. This function computes the one-dimensional discrete Fourier Transform.

# Compute FFT fft_result = np.fft.fft(signal) n = len(signal) freq = np.fft.fftfreq(n, d=1/fs) # Frequency bins # Take only positive frequencies and their corresponding FFT coefficients freq = freq[:n//2] fft_result = np.abs(fft_result[:n//2]) 

3. Plotting the FFT

Now, plot the frequency spectrum using Matplotlib:

plt.figure(figsize=(10, 6)) # Plot frequency spectrum plt.plot(freq, fft_result) plt.title('Fast Fourier Transform') plt.xlabel('Frequency (Hz)') plt.ylabel('Amplitude') plt.grid(True) plt.show() 

Complete Example

Here's how the complete code looks:

import numpy as np import matplotlib.pyplot as plt # Generate some data (sine wave) fs = 1000 # Sampling frequency t = np.linspace(0, 1, fs, endpoint=False) # Time vector from 0 to 1 second f = 5 # Frequency of the signal signal = np.sin(2 * np.pi * f * t) # Sine wave signal # Compute FFT fft_result = np.fft.fft(signal) n = len(signal) freq = np.fft.fftfreq(n, d=1/fs) # Frequency bins # Take only positive frequencies and their corresponding FFT coefficients freq = freq[:n//2] fft_result = np.abs(fft_result[:n//2]) # Plot frequency spectrum plt.figure(figsize=(10, 6)) plt.plot(freq, fft_result) plt.title('Fast Fourier Transform') plt.xlabel('Frequency (Hz)') plt.ylabel('Amplitude') plt.grid(True) plt.show() 

Explanation

  • Generating Data: Here, we generate a simple sine wave signal as an example. Replace signal with your actual data.

  • Computing FFT: np.fft.fft(signal) computes the FFT of signal. We also compute the corresponding frequency bins using np.fft.fftfreq().

  • Plotting: We plot the frequency spectrum (freq vs fft_result) using Matplotlib. Adjust the figure size, labels, and title as per your preference.

Additional Notes

  • Ensure your signal is properly sampled (fs should be appropriately chosen based on your signal's characteristics).
  • FFT gives you both magnitude and phase information. In this example, we only plot the magnitude (np.abs(fft_result)), but you can also plot the phase if needed (np.angle(fft_result)).
  • For real-world data, ensure it is properly pre-processed (windowing, detrending) to avoid artifacts in the frequency spectrum.

This example demonstrates a basic FFT plot in Python using NumPy and Matplotlib. Adjust it according to your specific data and analysis requirements.

Examples

  1. How to compute and plot FFT using numpy in Python?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(12, 6)) plt.subplot(121) plt.plot(time, signal) plt.title('Original Signal') plt.xlabel('Time') plt.ylabel('Amplitude') plt.subplot(122) plt.plot(frequencies, np.abs(fft_result)) plt.title('Fast Fourier Transform') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.tight_layout() plt.show() 

    Description: This code generates a sample sine wave signal, computes its FFT using numpy (np.fft.fft), and plots the original signal along with its FFT spectrum.

  2. Plot FFT of a real-valued signal using numpy?

    import numpy as np import matplotlib.pyplot as plt # Generate a real-valued signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.rfft(signal) frequencies = np.fft.rfftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, np.abs(fft_result)) plt.title('FFT of a Real-valued Signal') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code demonstrates how to compute and plot the FFT of a real-valued signal using np.fft.rfft in numpy, suitable for signals without complex values.

  3. How to plot FFT power spectrum with logarithmic scale?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, 20 * np.log10(np.abs(fft_result))) plt.title('FFT Power Spectrum (Logarithmic Scale)') plt.xlabel('Frequency') plt.ylabel('Power (dB)') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal, plots its power spectrum on a logarithmic scale using 20 * np.log10(np.abs(fft_result)), and visualizes the frequency domain in decibels (dB).

  4. How to plot FFT phase spectrum using numpy in Python?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Compute phase spectrum phase_spectrum = np.angle(fft_result) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, phase_spectrum) plt.title('FFT Phase Spectrum') plt.xlabel('Frequency') plt.ylabel('Phase') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal, calculates its phase spectrum using np.angle(fft_result), and plots the phase versus frequency.

  5. How to plot FFT with custom windowing function in numpy?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Define a custom windowing function window = np.hamming(len(signal)) # Compute FFT with windowing fft_result = np.fft.fft(signal * window) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, np.abs(fft_result)) plt.title('FFT with Hamming Window') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code applies a Hamming window (np.hamming) to a signal before computing its FFT, demonstrating how to use custom windowing functions in FFT analysis.

  6. How to plot FFT with high-resolution frequency axis?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, np.abs(fft_result)) plt.title('FFT with High-Resolution Frequency Axis') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.xlim(0, 10) # Adjust x-axis range for high resolution plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal and plots its frequency spectrum with a high-resolution frequency axis (plt.xlim(0, 10)) for detailed frequency analysis.

  7. Plot FFT magnitude and phase spectrum together in numpy?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Compute magnitude and phase spectrum magnitude_spectrum = np.abs(fft_result) phase_spectrum = np.angle(fft_result) # Plotting plt.figure(figsize=(12, 6)) plt.subplot(121) plt.plot(frequencies, magnitude_spectrum) plt.title('FFT Magnitude Spectrum') plt.xlabel('Frequency') plt.ylabel('Magnitude') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.subplot(122) plt.plot(frequencies, phase_spectrum) plt.title('FFT Phase Spectrum') plt.xlabel('Frequency') plt.ylabel('Phase') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal, calculates its magnitude (np.abs(fft_result)) and phase spectrum (np.angle(fft_result)), and plots both spectra together for comprehensive frequency analysis.

  8. How to plot FFT with normalized amplitude in numpy?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Normalize FFT amplitude fft_normalized = np.abs(fft_result) / len(signal) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, fft_normalized) plt.title('FFT with Normalized Amplitude') plt.xlabel('Frequency') plt.ylabel('Normalized Amplitude') plt.xlim(0, 5) # Limiting x-axis for better visualization plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal, normalizes its amplitude (np.abs(fft_result) / len(signal)), and plots the FFT spectrum with normalized amplitude for consistent analysis across different signal lengths.

  9. How to plot FFT with custom frequency range using numpy?

    import numpy as np import matplotlib.pyplot as plt # Generate a sample signal time = np.linspace(0, 10, 1000) frequency = 2 # Frequency of the signal amplitude = 5 # Amplitude of the signal signal = amplitude * np.sin(2 * np.pi * frequency * time) # Compute FFT fft_result = np.fft.fft(signal) frequencies = np.fft.fftfreq(len(signal), d=time[1]-time[0]) # Plotting plt.figure(figsize=(8, 4)) plt.plot(frequencies, np.abs(fft_result)) plt.title('FFT with Custom Frequency Range') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.xlim(0, 3) # Customizing x-axis range for specific frequency range plt.grid(True) plt.tight_layout() plt.show() 

    Description: This code computes the FFT of a signal and plots its frequency spectrum with a custom frequency range (plt.xlim(0, 3)) to focus on specific frequency components of interest.

  10. How to plot FFT of a 2D array using numpy and matplotlib?

    import numpy as np import matplotlib.pyplot as plt # Generate a 2D array (image data) data = np.random.random((100, 100)) # Compute 2D FFT fft_result = np.fft.fft2(data) fft_result_shifted = np.fft.fftshift(fft_result) # Plotting plt.figure(figsize=(10, 5)) plt.subplot(121) plt.imshow(data, cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(122) plt.imshow(np.log(1 + np.abs(fft_result_shifted)), cmap='gray') plt.title('2D FFT Spectrum') plt.axis('off') plt.tight_layout() plt.show() 

    Description: This code generates a random 2D array (data), computes its 2D FFT (np.fft.fft2), shifts the zero frequency component to the center (np.fft.fftshift), and visualizes both the original image and its 2D FFT spectrum.


More Tags

compilation profiling activity-finish row salesforce-lightning mvvm springfox esp32 cocoa angular-oauth2-oidc

More Programming Questions

More Tax and Salary Calculators

More Physical chemistry Calculators

More Fitness Calculators

More Mortgage and Real Estate Calculators