多个matplotlib specgram与共享颜色条

时间:2018-01-23 05:33:57

标签: python-3.x matplotlib

我有两个specgram,我需要使用相同的颜色条进行绘图。我试图关注以前的帖子,但我总是得到与imshow相关的错误或找到我的两个数据集之间的最小值和最大值。 到目前为止,我只是使用数据集的颜色栏,它可能具有最小值和最大值(噪声数据集)

NFFT = 1024
cmap = plt.get_cmap('viridis')
cmap.set_under(color='k', alpha=None)

x=noisy.as_matrix()[:,1]
z=denoised [:,1]
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(20, 10))
values, ybins, xbins, im = ax1.specgram(x, NFFT=NFFT, cmap=cmap, 
Fs=128, noverlap=900)
ax1.set(title='original')

values1, ybins1, xbins1, im1 = ax2.specgram(z, NFFT=NFFT, cmap=cmap, 
Fs=128, noverlap=900)
ax2.set(title='deoised')
fig.colorbar(im, ax=ax1)
fig.colorbar(im, ax=ax2)

plt.show()

enter image description here

我的问题是如何分享两个参数之间的颜色图以及如何找到最小值和最大值?

1 个答案:

答案 0 :(得分:2)

您可以使用mlab.specgram()绘制信号之前获取信号的光谱内容。然后,您可以在两个光谱中找到最小值和最大值,并相应地标准化您的颜色条。

以下不是效率最高的代码,因为我计算两次光谱,一次使用mlab.specgram(),另一次使用Axes.specgram(),但它可以完成工作。如果你查看Axes.specgram()的代码,你可以弄清楚如何绘制光谱图而不重新计算光谱,但我没有花时间去弄清楚它。

信号数据来自specgram_demo

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import mlab as mlab

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)

# create a transient "chirp"
mask = np.where(np.logical_and(t > 10, t < 12), 1.0, 0.0)
s2 = s2 * mask

# add some noise into the mix
nse = 0.01*np.random.random(size=len(t))

x = s1 + s2 + nse  # the signal
z = x * 50
NFFT = 1024       # the length of the windowing segments
Fs = int(1.0/dt)  # the sampling frequency

spectrum1, freqs1, t1 = mlab.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
spectrum2, freqs2, t2 = mlab.specgram(z, NFFT=NFFT, Fs=Fs, noverlap=900)

min_val = 10 * np.log10(min(spectrum1.min(), spectrum2.min()))
max_val = 10 * np.log10(min(spectrum1.max(), spectrum2.max()))


gs0 = gs.GridSpec(2,2, width_ratios=[10,0.1])
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(gs0[0,0])
ax2 = fig.add_subplot(gs0[1,0])
cax = fig.add_subplot(gs0[:,1])
spectrum1, freqs1, t1, im1 = ax1.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900, cmap=cmap, vmin=min_val, vmax=max_val)
ax1.set(title='original')

spectrum2, freqs2, t2, im2 = ax2.specgram(z, NFFT=NFFT, Fs=Fs, noverlap=900, cmap=cmap, vmin=min_val, vmax=max_val)
ax2.set(title='denoised')
fig.colorbar(im1, cax=cax)

fig.tight_layout()

enter image description here