Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot signal in Matplotlib in Python?
Signal plotting in Matplotlib involves creating time-series visualizations that show how signal amplitude changes over time. This is essential for analyzing waveforms, noise patterns, and signal processing applications.
Basic Signal Plot
Let's create a simple sinusoidal signal with noise to demonstrate signal plotting ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Set random seed for reproducible results
np.random.seed(0)
# Define sampling parameters
dt = 0.01 # sampling interval
Fs = 1 / dt # sampling frequency
t = np.arange(0, 10, dt)
# Generate noise
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
# Create signal: sine wave + noise
s = 0.1 * np.sin(4 * np.pi * t) + cnse
# Create the plot
fig, axs = plt.subplots()
axs.set_title("Signal")
axs.plot(t, s, color='C0')
axs.set_xlabel("Time")
axs.set_ylabel("Amplitude")
plt.show()
Multiple Signal Comparison
You can plot multiple signals on the same axes for comparison ?
import matplotlib.pyplot as plt
import numpy as np
# Time parameters
t = np.linspace(0, 2 * np.pi, 100)
# Different signals
signal1 = np.sin(t)
signal2 = np.sin(2 * t)
signal3 = np.sin(t) + 0.5 * np.sin(3 * t)
# Plot multiple signals
plt.figure(figsize=(10, 6))
plt.plot(t, signal1, label='sin(t)', linewidth=2)
plt.plot(t, signal2, label='sin(2t)', linewidth=2)
plt.plot(t, signal3, label='sin(t) + 0.5*sin(3t)', linewidth=2)
plt.title('Multiple Signal Comparison')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Signal Processing Steps
| Step | Purpose | Code Element |
|---|---|---|
| Set sampling rate | Define time resolution | dt = 0.01 |
| Create time array | Generate time points | t = np.arange(0, 10, dt) |
| Generate signal | Create waveform data | s = 0.1 * np.sin(4 * np.pi * t) |
| Add noise | Simulate real−world conditions | s + cnse |
Key Parameters
- Sampling interval (dt) − Time between consecutive samples
- Sampling frequency (Fs) − Number of samples per second
- Time array (t) − Sequence of time points for the signal
- Signal amplitude − Magnitude of the waveform at each time point
Conclusion
Signal plotting in Matplotlib requires defining time parameters, generating signal data, and using plot() with proper labels. The key is setting appropriate sampling rates and adding meaningful annotations for clear visualization.
Advertisements
