matplotlib 如何绘制wav谱图文件的2个子图?

d6kp6zgx  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(200)

我有2个WAV文件(相同的采样率),我想并排显示他们的频谱图。
我使用的代码从这里(https://librosa.org/doc/main/generated/librosa.feature.melspectrogram.html)显示wav文件谱图:

y, sr             = librosa.load(FILE_NO_SPEAKING)
mel_spec_no_speak = librosa.feature.melspectrogram(y=y, sr=sr)

y, sr             = librosa.load(FILE_SPEAKING)
mel_spec_speak    = librosa.feature.melspectrogram(y=y, sr=sr)

D = np.abs(librosa.stft(y))**2
S = librosa.feature.melspectrogram(S=D, sr=sr)

fig, (ax1, ax2) = plt.subplots(1, 2)

S_dB          = librosa.power_to_db(S, ref=np.max)
img_no_speak  = librosa.display.specshow(S_dB, 
                                x_axis='time',
                                y_axis='mel', 
                                sr=sr,
                                fmax=8000, 
                                ax=ax1)

img_speak     = librosa.display.specshow(S_dB, 
                                x_axis='time',
                                y_axis='mel', 
                                sr=sr,
                                fmax=8000, 
                                ax=ax2)

#fig.colorbar(?, ax=(ax1, ax2), format='%+2.0f dB')
ax1.set(title='No Speak')
ax2.set(title='Speak')
  • 但是我不知道如何设置每个子情节图像的颜色条?
  • 另外我想放大图的出图尺寸,怎么做呢?
7xllpg7q

7xllpg7q1#

要使用每个子图的图像设置颜色条,您可以使用fig.colorbar()为整个图形创建一个颜色条,并将img_no_speak对象作为可Map参数传入。下面是一个示例,并使用Librosa的波形生成图像:

import librosa
import matplotlib.pyplot as plt
import numpy as np

# Load trumpet signal for both cases
y, sr = librosa.load(librosa.ex("trumpet"))
mel_spec_no_speak = librosa.feature.melspectrogram(y=y, sr=sr)
y, sr = librosa.load(librosa.ex("trumpet"))
mel_spec_speak = librosa.feature.melspectrogram(y=y, sr=sr)

# Transform
D = np.abs(librosa.stft(y)) ** 2
S = librosa.feature.melspectrogram(S=D, sr=sr)

# Create figure, set up figure size in inches
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# Turn to dB, and show
S_dB = librosa.power_to_db(mel_spec_no_speak, ref=np.max)
img_no_speak = librosa.display.specshow(
    S_dB, x_axis="time", y_axis="mel", sr=sr, fmax=8000, ax=ax1
)
ax1.set(title="No Speak")

# Turn to dB, and show
S_dB = librosa.power_to_db(mel_spec_speak, ref=np.max)
img_speak = librosa.display.specshow(
    S_dB, x_axis="time", y_axis="mel", sr=sr, fmax=8000, ax=ax2
)
ax2.set(title="Speak")

# Global colorbar
fig.colorbar(img_no_speak, ax=[ax1, ax2], format="%+2.0f dB")

# Show
plt.show()

要放大图形绘图大小,可以在创建图形时将figsize参数传递给subplots()函数。例如,要创建宽12英寸、高6英寸的图形,可以使用figsize=(12, 6)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

相关问题