Vibration Analysis in Python with FFT: Find Machine Faults from the Spectrum

A vibration signal from a running machine looks like noise in the time domain. The Fast Fourier Transform (FFT) turns it into a spectrum where each fault shows up as a peak at its own frequency. That is the basis of condition monitoring in industry. In this tutorial we do vibration analysis in Python with FFT: build a realistic accelerometer signal, compute a correctly scaled amplitude spectrum and identify unbalance, misalignment and a bearing defect from the peaks.

Quick answer: In Python, multiply the signal by a Hann window, take np.fft.rfft(), and scale the magnitude as amplitude = 2·|X| / Σw. Use np.fft.rfftfreq(N, 1/fs) for the frequency axis. The frequency resolution is Δf = fs/N and the highest frequency you can see is fs/2. In our example the spectrum recovers the 2.00, 0.81 and 0.50 m/s² components at 25, 50 and 107 Hz.

The Problem

  • A motor-pump set running at 1500 rpm, so the running speed is 25 Hz
  • Accelerometer on the bearing housing, sampled at fs = 2000 Hz for 2 s (4000 samples)
  • The signal contains unbalance (2.0 m/s² at 1x), misalignment (0.8 m/s² at 2x), a bearing outer-race defect (0.5 m/s² at 107 Hz) and random noise

We want to find each component from the signal alone, as you would with measured data. Here we build the signal ourselves so we know the right answer and can check the method. With a real accelerometer file, you only replace the signal line with np.loadtxt().

Step 1: The Theory

The FFT breaks a signal into sine waves and tells you how strong each frequency is. Three numbers control what you can see:

  • Nyquist frequency = fs/2 = 1000 Hz. Anything above this cannot be measured and folds back as a false peak (aliasing).
  • Frequency resolution Δf = fs/N = 1/T = 0.5 Hz. A longer record separates close peaks better.
  • Amplitude scaling: the raw FFT magnitude grows with N, so it must be scaled. For a single-sided spectrum with a window w, amplitude = 2|X|/Σw.

As a cross-check, the overall RMS of the signal should match the sum of its parts: √[(2.0² + 0.8² + 0.5²)/2 + 0.5²] = 1.64 m/s². Each sine wave contributes A²/2 and the noise contributes its variance.

Fault frequencies are usually given as orders, multiples of running speed: unbalance at 1x, misalignment at 2x (sometimes 1x and 3x), looseness at many harmonics. Bearing defects appear at non-integer orders that depend on the bearing geometry. Here 107 Hz is 4.28x.

Step 2: The Python Code

You need Python with NumPy and Matplotlib (pip install numpy matplotlib). The random noise uses a fixed seed, so your output will match ours exactly. The peak finder is a simple local-maximum test written in NumPy, so no extra library is needed.

import numpy as np
import matplotlib.pyplot as plt

# ---- Simulated accelerometer signal from a motor-pump bearing housing ----
fs = 2000            # sampling rate, Hz
T = 2.0              # record length, s
t = np.arange(0, T, 1 / fs)
N = len(t)

rpm = 1500
f1 = rpm / 60        # running speed (1x), Hz
f_bpfo = 107.0       # outer-race bearing defect frequency, Hz

rng = np.random.default_rng(42)        # fixed seed so results repeat
signal = (2.0 * np.sin(2 * np.pi * f1 * t)            # imbalance (1x)
          + 0.8 * np.sin(2 * np.pi * 2 * f1 * t + 0.5)  # misalignment (2x)
          + 0.5 * np.sin(2 * np.pi * f_bpfo * t + 1.0)  # bearing defect
          + 0.5 * rng.standard_normal(N))               # random noise, m/s^2

# ---- FFT: single-sided amplitude spectrum with a Hann window ----
window = np.hanning(N)
X = np.fft.rfft(signal * window)
freqs = np.fft.rfftfreq(N, 1 / fs)
amp = 2 * np.abs(X) / np.sum(window)   # corrects for window and two sides

# ---- Find the main peaks (local maxima above a threshold) ----
threshold = 0.2   # m/s^2
is_peak = (amp[1:-1] > amp[:-2]) & (amp[1:-1] > amp[2:]) & (amp[1:-1] > threshold)
peak_idx = np.where(is_peak)[0] + 1

print(f"Samples: {N}, frequency resolution: {fs/N:.2f} Hz, Nyquist: {fs/2:.0f} Hz")
print(f"Overall RMS acceleration: {np.sqrt(np.mean(signal**2)):.2f} m/s^2\n")
print("Peak (Hz)  Amplitude (m/s^2)  Order   Likely cause")
for i in peak_idx:
    order = freqs[i] / f1
    if abs(order - 1) < 0.05:
        cause = "imbalance (1x)"
    elif abs(order - 2) < 0.05:
        cause = "misalignment (2x)"
    elif abs(freqs[i] - f_bpfo) < 1:
        cause = "bearing outer race (BPFO)"
    else:
        cause = "check"
    print(f"{freqs[i]:8.1f}   {amp[i]:10.2f}         {order:5.2f}   {cause}")

# ---- Plot time signal and spectrum ----
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9, 6))
ax1.plot(t[:400] * 1000, signal[:400], lw=1)
ax1.set_xlabel("Time (ms)")
ax1.set_ylabel("Acceleration (m/s²)")
ax1.set_title("Time signal (first 0.2 s)")
ax1.grid(True, alpha=0.3)

ax2.plot(freqs, amp, lw=1)
for i in peak_idx:
    ax2.annotate(f"{freqs[i]:.0f} Hz", (freqs[i], amp[i]), textcoords="offset points",
                 xytext=(5, 5))
ax2.set_xlim(0, 250)
ax2.set_xlabel("Frequency (Hz)")
ax2.set_ylabel("Amplitude (m/s²)")
ax2.set_title("FFT spectrum (Hann window)")
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("vibration_fft.png", dpi=150)
plt.show()

Step 3: The Results

Running the script prints:

Samples: 4000, frequency resolution: 0.50 Hz, Nyquist: 1000 Hz
Overall RMS acceleration: 1.64 m/s^2

Peak (Hz)  Amplitude (m/s^2)  Order   Likely cause
    25.0         2.00          1.00   imbalance (1x)
    50.0         0.81          2.00   misalignment (2x)
   107.0         0.50          4.28   bearing outer race (BPFO)

The FFT recovers all three amplitudes we put in (2.0, 0.8 and 0.5 m/s²) to within 0.01 m/s², and the RMS matches the hand calculation. Those are the two checks that prove the scaling is right. The plot shows the signal and its spectrum:

Vibration time signal and FFT spectrum in Python showing imbalance, misalignment and bearing defect peaks
Time signal and FFT spectrum of a simulated bearing housing vibration at 1500 rpm, computed with Python.

What the Graph Tells You

  • The time signal hides the faults. You can see the 25 Hz wave, but the 50 Hz and 107 Hz parts are lost in the noise.
  • The spectrum separates them clearly. Three sharp peaks stand far above the noise floor of about 0.02 m/s².
  • The 1x peak is the largest, so unbalance is the main problem here. Balancing the rotor would remove most of the vibration.
  • The 107 Hz peak is small but important. Bearing defects start small and grow. Trending this peak over weeks is how maintenance teams plan a bearing change before it fails.

Common Mistakes

  • Not scaling the FFT – plotting abs(np.fft.fft(x)) directly gives numbers thousands of times too large.
  • Forgetting the window correction – the Hann window halves the amplitude. Dividing by N instead of Σw gives peaks that are 50 % low.
  • Sampling too slowly – with fs below twice the highest frequency, peaks appear at the wrong place (aliasing).
  • Using the full two-sided FFT – the second half of np.fft.fft is a mirror image. Use rfft and double the amplitude.

Try It Yourself: Extend the Code

  1. Change the record length to 0.5 s and see how the peaks get wider (poorer resolution).
  2. Remove the window and compare the leakage around each peak.
  3. Integrate the acceleration spectrum to velocity in mm/s and compare the RMS with ISO severity zones.
  4. Add envelope analysis (Hilbert transform) to find bearing defects hidden under high-frequency resonance.
  5. Record real data from a small motor with a phone or low-cost accelerometer and compare healthy and unbalanced conditions.

Steps 3 to 5 together make a good Python-based condition monitoring project. Feed the spectrum peaks to a classifier and it becomes one of our machine learning projects. For a design-side view of vibration, see our cracked shaft vibration and crack detection project, and for theory revision read our theory of machines viva questions. New to arrays? Start with NumPy basics.

More Python for Engineers tutorials: beam deflection in Python, spur gear design in Python, Otto vs Diesel cycle in Python, heat exchanger design in Python (LMTD method) and how to plot CFD and FEA results with Python Matplotlib.

Learn Python for Mechanical Engineering

This tutorial is part of how we teach Python to mechanical students – through real engineering problems, not abstract examples. In our Python for mechanical engineers classes you learn NumPy, Matplotlib, signal processing and data handling step by step, in live screen-share sessions or recorded videos, and write the code yourself.

Frequently Asked Questions

How do you do an FFT of a vibration signal in Python?

Load or generate the signal as a NumPy array, multiply it by a window such as np.hanning(N), take np.fft.rfft, and scale the magnitude by 2/sum(window) to get the true amplitude. np.fft.rfftfreq(N, 1/fs) gives the matching frequency axis.

Why do we use a Hann window before the FFT?

A measured record rarely contains a whole number of cycles, so the ends do not join smoothly and energy leaks into nearby frequencies. The Hann window tapers both ends to zero, which reduces this leakage. Because it also lowers the amplitude, you divide by the sum of the window to correct it.

What does a 1x peak in a vibration spectrum mean?

A peak at the running speed (1x, here 25 Hz for 1500 rpm) is the classic sign of unbalance. A strong 2x peak often points to misalignment, and peaks that are not whole multiples of running speed can come from bearing defects or other sources.

What sampling rate do I need for vibration analysis?

At least twice the highest frequency you want to see (the Nyquist limit), and in practice 2.5 times or more. To check bearing frequencies up to 250 Hz, sampling at 2000 Hz gives plenty of margin, and a 2 s record gives 0.5 Hz resolution.

Is vibration analysis with FFT a good final year project?

Yes, especially with real data. Record vibration from a small motor or test rig with an accelerometer, compare healthy and faulty conditions in the FFT, and then use the spectrum peaks as features for a machine learning fault classifier.

Start Learning

Tell us your branch and what you want to build. Message us on WhatsApp or use the enquiry form on our home page.

Interested in this project? Get the details, files and guidance from our team.

Enquire on WhatsApp

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top