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 place X-axis grid over a spectrogram in Python Matplotlib?
To place X-axis grid over a spectrogram in Python Matplotlib, we can use the grid() method with specific axis parameters. This technique helps visualize time intervals clearly on both the signal plot and spectrogram.
Creating a Signal with Noise
First, let's create a composite signal with two sine waves and noise ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure parameters
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create time array
dt = 0.0005
t = np.arange(0.0, 20.0, dt)
# Create composite signal
s1 = np.sin(2 * np.pi * 100 * t) # 100 Hz sine wave
s2 = 2 * np.sin(2 * np.pi * 400 * t) # 400 Hz sine wave
s2[t <= 10] = s2[12 <= t] = 0 # Make s2 zero outside 10-12 seconds
# Add noise
nse = 0.01 * np.random.random(size=len(t))
x = s1 + s2 + nse
print(f"Signal length: {len(x)} samples")
print(f"Time duration: {t[-1]} seconds")
Signal length: 40000 samples Time duration: 19.9995 seconds
Plotting Signal and Spectrogram with X-axis Grid
Now we'll create subplots showing both the time-domain signal and its spectrogram with X-axis grids ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure parameters
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create time and signal data
dt = 0.0005
t = np.arange(0.0, 20.0, dt)
s1 = np.sin(2 * np.pi * 100 * t)
s2 = 2 * np.sin(2 * np.pi * 400 * t)
s2[t <= 10] = s2[12 <= t] = 0
nse = 0.01 * np.random.random(size=len(t))
x = s1 + s2 + nse
# Spectrogram parameters
NFFT = 1024
Fs = int(1.0 / dt)
# Create subplots
fig, (ax1, ax2) = plt.subplots(nrows=2)
# Plot time-domain signal with X-axis grid
ax1.plot(t, x)
ax1.grid(axis="x", ls="dotted", lw=2, color="red")
ax1.margins(x=0)
ax1.set_ylabel('Amplitude')
ax1.set_title('Time Domain Signal')
# Plot spectrogram with X-axis grid
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax2.grid(axis="x", ls="dotted", lw=2, color="red")
ax2.set_ylabel('Frequency (Hz)')
ax2.set_xlabel('Time (seconds)')
ax2.set_title('Spectrogram with X-axis Grid')
plt.tight_layout()
plt.show()
Grid Customization Options
You can customize the grid appearance using different parameters ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
dt = 0.001
t = np.arange(0.0, 10.0, dt)
x = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 120 * t)
NFFT = 512
Fs = int(1.0 / dt)
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# Different grid styles
grid_styles = [
{"ls": "solid", "lw": 1, "color": "gray", "alpha": 0.5},
{"ls": "dashed", "lw": 1.5, "color": "blue", "alpha": 0.7},
{"ls": "dotted", "lw": 2, "color": "red", "alpha": 0.8},
{"ls": "dashdot", "lw": 1, "color": "green", "alpha": 0.6}
]
titles = ["Solid Grid", "Dashed Grid", "Dotted Grid", "Dash-dot Grid"]
for i, (ax, style, title) in enumerate(zip(axes.flat, grid_styles, titles)):
Pxx, freqs, bins, im = ax.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=256)
ax.grid(axis="x", **style)
ax.set_title(title)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Frequency (Hz)')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
axis |
Which axis to show grid | 'x', 'y', 'both' |
ls or linestyle
|
Line style | 'solid', 'dashed', 'dotted' |
lw or linewidth
|
Line width | 1, 2, 2.5 |
color |
Grid color | 'red', 'blue', '#FF5733' |
alpha |
Transparency | 0.0 to 1.0 |
Conclusion
Use ax.grid(axis="x") to add X-axis grids over spectrograms. Customize appearance with linestyle, color, and transparency parameters for better visualization. The grid helps align time features between signal and frequency representations.
Advertisements
