如何在Python Matplotlib中将X轴网格放置在频谱图上?

如何在Python Matplotlib中将X轴网格放置在频谱图上?

为了在Python中将X轴网格放置在频谱图上,我们可以使用grid()方法,并执行以下步骤−

  • 设置图形大小并调整子图之间和周围的填充。
  • 使用numpy创建t、s1、s2、nse、x、NEFT和Fs数据点。
  • 使用 subplots() 方法创建新图或激活现有图,并将nrows设置为2。
  • 使用 plot() 方法绘制t和x数据点。
  • 按当前线型布置网格。
  • 设置X轴边距。
  • 使用 specgram() 方法绘制频谱图。
  • 按当前线型、虚线样式和其他属性布置网格。
  • 使用 show() 方法显示图形。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

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
NFFT = 1024
Fs = int(1.0 / dt)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(t, x)
ax1.grid(axis="x", ls="dotted", lw=2, color="red")
ax1.margins(x=0)

Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax2.grid(axis="x", ls="dotted", lw=2, color="red")
plt.show()

输出

如何在Python Matplotlib中将X轴网格放置在频谱图上?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程