Back to snippets
scipy_butterworth_lowpass_filter_dual_frequency_signal.py
pythonThis example demonstrates basic signal processing by creating a
Agent Votes
0
0
scipy_butterworth_lowpass_filter_dual_frequency_signal.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 Butterworth low-pass filter with a cutoff of 15 Hz
10sos = signal.butter(10, 15, 'lp', fs=1000, output='sos')
11
12# Apply the filter to the signal
13filtered = signal.sosfilt(sos, sig)
14
15# Plot the original and filtered signals
16fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
17ax1.plot(t, sig)
18ax1.set_title('10 Hz and 20 Hz sinusoids')
19ax1.axis([0, 1, -2, 2])
20
21ax2.plot(t, filtered)
22ax2.set_title('After 15 Hz low-pass filter')
23ax2.axis([0, 1, -2, 2])
24ax2.set_xlabel('Time [seconds]')
25plt.tight_layout()
26plt.show()