5 Best Ways to Plot Signals in Matplotlib in Python

πŸ’‘ Problem Formulation: When working with digital signal processing or data analysis in Python, visualizing data is crucial. Users often seek to create clear and informative signal plots to analyze variations, frequencies, and patterns over time. This article explores different methods to plot signals using the popular library Matplotlib, where the input is a signal in the form of a numerical array, and the desired output is a graphical representation of that signal.

Method 1: Basic Line Plot

Creating a basic line plot is the simplest method to visualize a signal in Matplotlib. The function pyplot.plot() from Matplotlib is used to draw continuous signal representations by connecting data points with straight lines. This method is ideal for quickly inspecting the general shape and nature of the signal.

Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

# Create a time array and a sample signal (sine wave)
t = np.linspace(0, 1, 500)
signal = np.sin(2 * np.pi * 5 * t)

# Plot the signal
plt.plot(t, signal)
plt.title('Basic Line Plot of a Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.show()

Output: A line plot appearing on the screen, depicting the sine wave signal across the specified time interval.

This code snippet generates a basic line plot. The array t represents time, and signal represents the signal’s amplitude at each time point. The plt.plot() function then draws the signal, and various labeling functions provide context to the plot, such as the title, x-label, and y-label.

Method 2: Subplots for Multiple Signals

When plotting multiple signals, using subplots is a tidy way to display comparative data. Matplotlib’s plt.subplots() function facilitates the creation of a figure with a grid of subplots. Each subplot can contain a different signal, making it easier to analyze differences and similarities between them.

Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

# Create signals
t = np.linspace(0, 1, 500)
signal1 = np.sin(2 * np.pi * 5 * t)
signal2 = np.sin(2 * np.pi * 10 * t)

# Create a 2x1 grid of subplots
fig, axs = plt.subplots(2, 1)

# Plot each signal on a separate subplot
axs[0].plot(t, signal1)
axs[0].set_title('5 Hz Sine Wave')

axs[1].plot(t, signal2)
axs[1].set_title('10 Hz Sine Wave')

# Display the plot
plt.tight_layout()
plt.show()

Output: A figure with two subplots, each displaying a different sine wave signal corresponding to different frequencies.

The code snippet utilizes plt.subplots() to make a grid of 2 rows and 1 column. The variables axs[0] and axs[1] are then employed to plot the two different signals in individual subplots, thus allowing for a side-by-side comparison.

Method 3: Spectrogram

A spectrogram displays signal strength over time at various frequencies and is useful for analyzing the frequency components of a signal. In Matplotlib, the specgram() method of a matplotlib.pyplot object creates a spectrogram of the signal.

Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

# Create a signal with varying frequency
t = np.linspace(0, 2, 2000)
signal = np.sin(2 * np.pi * t * (2 + 3 * t))

# Plot the spectrogram
plt.specgram(signal, Fs=1000)
plt.title('Spectrogram of a Time-Varying Signal')
plt.xlabel('Time [s]')
plt.ylabel('Frequency [Hz]')
plt.colorbar(label='Intensity [dB]')
plt.show()

Output: A spectrogram plot showing the intensity of various frequencies over time for the constructed signal.

In this script, plt.specgram() is used to generate the spectrogram of a time-varying frequency signal. The Fs parameter specifies the sampling frequency. The colorbar provides additional information about the signal’s intensity at different frequencies and times.

Method 4: Interactive Plots with Widgets

Interactive plots allow users to explore data dynamically by zooming, panning, or updating the plot with widgets. Matplotlib’s widget tools can enhance the user experience significantly. The function plt.subplots() is paired with widgets like sliders to adjust the parameters of the signal in real-time.

Here’s an example:

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
t = np.linspace(0, 1, 500)
initial_freq = 5
signal = np.sin(2 * np.pi * initial_freq * t)
line, = plt.plot(t, signal)

axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(axfreq, 'Frequency', 0.1, 30.0, valinit=initial_freq)

# Update the plot with the change from the slider
def update(val):
    line.set_ydata(np.sin(2 * np.pi * val * t))
    fig.canvas.draw_idle()

freq_slider.on_changed(update)
plt.show()

Output: An interactive plot with a slider widget allowing the user to adjust the frequency of the displayed sine wave signal.

This code block enhances a basic plot with an interactive slider that changes the wave’s frequency. The Slider object is created with a specified frequency range, and a handler function update() redraws the plot with the new frequency when the slider is moved.

Bonus One-Liner Method 5: Plotting a Signal with Marker Styles

For a quick visualization of discrete data points in a signal, you can add marker styles to the plot. Matplotlib provides various marker styles, which can be useful for highlighting individual sample points on a continuous signal.

Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 1, 50)
signal = np.sin(2 * np.pi * 5 * t)

plt.plot(t, signal, marker='o', linestyle='')
plt.title('Signal with Marker Styles')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.show()

Output: A plot showing the individual data points of the signal with circle markers.

The one-liner code demonstrates plotting a signal with marker styles by specifying the marker and linestyle arguments in plt.plot(). This method creates a scatter plot-like visualization of the signal samples.

Summary/Discussion

  • Method 1: Basic Line Plot. Simple and straightforward. Best for a quick look at a signal. Limited when analyzing complex data or multiple signals.
  • Method 2: Subplots for Multiple Signals. Great for comparisons. Allows for organized visualization of various signals. Requires more setup for arranging subplots appropriately.
  • Method 3: Spectrogram. Perfect for frequency analysis over time. Ideal for signals that change frequencies. May be complex for beginners.
  • Method 4: Interactive Plots with Widgets. Provides interactive data exploration. Engages the user to experiment with signal parameters. Requires understanding of event handling and widgets.
  • Bonus One-Liner Method 5: Plotting a Signal with Marker Styles. Quick and convenient for spotting individual data points. Not suitable for detailed analysis of continuous signals.