How to Use Matplotlib for Signal Plotting in Python
Use
matplotlib.pyplot.plot() to draw signal data points on a graph. Prepare your signal as a list or array of values, then call plot() with time or sample indices on the x-axis and signal values on the y-axis. Customize labels and titles with xlabel(), ylabel(), and title() for clarity.Syntax
The basic syntax to plot a signal using matplotlib is:
plt.plot(x, y): Plots y-values against x-values (time or sample indices).plt.xlabel('label'): Adds a label to the x-axis.plt.ylabel('label'): Adds a label to the y-axis.plt.title('title'): Adds a title to the plot.plt.show(): Displays the plot window.
python
import matplotlib.pyplot as plt plt.plot(x, y) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title('Signal Plot') plt.show()
Example
This example shows how to plot a simple sine wave signal over time using matplotlib.
python
import numpy as np import matplotlib.pyplot as plt # Create time values from 0 to 1 second, 500 points fs = 500 # Sampling frequency T = 1 # Duration in seconds t = np.linspace(0, T, fs, endpoint=False) # Create a sine wave signal with frequency 5 Hz freq = 5 signal = np.sin(2 * np.pi * freq * t) # Plot the signal plt.plot(t, signal) plt.xlabel('Time (seconds)') plt.ylabel('Amplitude') plt.title('5 Hz Sine Wave Signal') plt.grid(True) plt.show()
Output
A line plot window showing a smooth sine wave oscillating 5 times over 1 second with labeled axes and grid.
Common Pitfalls
Common mistakes when plotting signals with matplotlib include:
- Not matching the x-axis length to the y-axis signal length, causing errors or distorted plots.
- Forgetting to call
plt.show(), so the plot window does not appear. - Using integer indices as x-axis without labeling, which can confuse interpretation.
- Plotting raw data without scaling or filtering, which may produce noisy or unclear graphs.
python
import matplotlib.pyplot as plt # Wrong: x and y lengths differ x = [0, 1, 2] y = [1, 2] # plt.plot(x, y) # This will raise a ValueError # Right: matching lengths x = [0, 1, 2] y = [1, 2, 3] plt.plot(x, y) plt.show()
Output
A simple line plot with points at (0,1), (1,2), and (2,3) displayed correctly.
Quick Reference
| Function | Purpose | Example |
|---|---|---|
| plt.plot(x, y) | Plot y vs x data points | plt.plot(t, signal) |
| plt.xlabel('label') | Set x-axis label | plt.xlabel('Time (s)') |
| plt.ylabel('label') | Set y-axis label | plt.ylabel('Amplitude') |
| plt.title('title') | Set plot title | plt.title('Signal Plot') |
| plt.grid(True) | Show grid lines | plt.grid(True) |
| plt.show() | Display the plot window | plt.show() |
Key Takeaways
Use plt.plot(x, y) to graph signal values against time or sample indices.
Always label axes and add a title for clear signal visualization.
Ensure x and y data arrays have the same length to avoid errors.
Call plt.show() to display the plot window after plotting.
Use grid lines to improve readability of signal plots.