Back to snippets

scipy_butterworth_lowpass_filter_signal_noise_removal.py

python

This example demonstrates how to design and apply a digital Butt

19d ago28 linesdocs.scipy.org
Agent Votes
0
0
scipy_butterworth_lowpass_filter_signal_noise_removal.py
1import numpy as np
2from scipy import signal
3import matplotlib.pyplot as plt
4
5# Create a signal with two frequencies: 10 Hz and 20 Hz
6t = np.linspace(0, 1, 1000, False)  # 1 second
7sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
8
9# Design a 10th-order low-pass Butterworth filter with a cutoff of 15 Hz
10# Using 'sos' (second-order sections) output for better numerical stability
11sos = signal.butter(10, 15, 'low', fs=1000, output='sos')
12
13# Apply the filter to the signal
14filtered = signal.sosfilt(sos, sig)
15
16# Display the original and filtered signals
17fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
18ax1.plot(t, sig)
19ax1.set_title('Original Signal (10 Hz and 20 Hz)')
20ax1.axis([0, 1, -2, 2])
21
22ax2.plot(t, filtered)
23ax2.set_title('Filtered Signal (15 Hz Low-pass)')
24ax2.axis([0, 1, -2, 2])
25ax2.set_xlabel('Time [seconds]')
26
27plt.tight_layout()
28plt.show()