使用 matplotlib.pyplot
绘制了包含两个信号的时域图和它们的相干图。
-
导入库和设置随机种子:
import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801)
这里导入了
matplotlib.pyplot
和numpy
库,并设置了随机种子以确保可重现性。 -
生成时间向量和信号:
dt = 0.01 t = np.arange(0, 30, dt) nse1 = np.random.randn(len(t)) nse2 = np.random.randn(len(t)) s1 = np.sin(2 * np.pi * 10 * t) + nse1 s2 = np.sin(2 * np.pi * 10 * t) + nse2
定义了时间步长
dt
和时间向量t
,然后生成了两个包含白噪声的信号nse1
和nse2
,以及包含与 10 Hz 频率相干的正弦波部分的信号s1
和s2
。 -
创建画布和子图:
fig, axs = plt.subplots(2, 1, layout='constrained')
使用
plt.subplots
创建一个包含两个子图的画布,axs
是一个包含两个 Axes 对象的数组。 -
绘制时域图:
axs[0].plot(t, s1, t, s2) axs[0].set_xlim(0, 2) axs[0].set_xlabel('Time (s)') axs[0].set_ylabel('s1 and s2') axs[0].grid(True)
在第一个子图中绘制了两个信号
s1
和s2
的时域图,并设置了横轴范围、标签和网格。 -
计算并绘制相干图:
cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt) axs[1].set_ylabel('Coherence')
使用
cohere
函数计算并绘制s1
和s2
的相干图,其中256
是 FFT 窗口大小,1. / dt
是采样频率。 -
显示图形:
plt.show()
最后,通过
plt.show()
显示整个图形。
- 完整代码
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# 定义时间步长和时间向量
dt = 0.01
t = np.arange(0, 30, dt)
# 生成两个包含白噪声的信号,以及一个与10 Hz频率相干的部分
nse1 = np.random.randn(len(t)) # 白噪声 1
nse2 = np.random.randn(len(t)) # 白噪声 2
s1 = np.sin(2 * np.pi * 10 * t) + nse1 # 信号 1 包含10 Hz的相干部分
s2 = np.sin(2 * np.pi * 10 * t) + nse2 # 信号 2 包含10 Hz的相干部分
# 创建一个包含两个子图的画布
fig, axs = plt.subplots(2, 1, layout='constrained')
# 绘制时域图
axs[0].plot(t, s1, t, s2)
axs[0].set_xlim(0, 2)
axs[0].set_xlabel('Time (s)')
axs[0].set_ylabel('s1 and s2')
axs[0].grid(True)
# 计算并绘制相干图
cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt)
axs[1].set_ylabel('Coherence')
# 显示图形
plt.show()