如何在单个图形上绘制声波、mfcc 和梅尔频谱图?

How to plot the sound wave, mfcc,and mel spectrogram on a single figure?

我有一个包含多个 wav 文件的文件夹(目前有 4 个)。我想连续绘制 wav、它的 mfcc 和 mel 频谱图,所以最后一个图有 12 个图(每行有三个图,因此有四行)。我无法绘制图表,只能提取特征。请有人帮忙解决这个 for 循环。我的意思是如何使用 subplot 命令以及如何在循环中存储每个图形。

此致

path=glob.glob('the path having four wav files/*.wav')

for p in path:
    y, sr = librosa.load(p, sr=16000)
    mfcc=librosa.feature.mfcc(y)
    S = librosa.feature.melspectrogram(y, sr)
    fig, ax = plt.subplot(4,3,.....)
    librosa.display.waveplot(y, sr=sr)
    librosa.display.specshow(librosa.power_to_db(S, ref=np.max))
    librosa.display.specshow(mfcc, x_axis="time",y_axis="mel")
    plt.show()
import matplotlib.pyplot as plt
Arrays=np.random.rand(6,10,10)
N_figures=Arrays.shape[0]
for Id in range(1,N_figures+1):
    Array=Arrays[Id-1]
    plt.subplot(N_figures/2,N_figures/3,Id)
    plt.imshow(Array)

您只需将 imshow 更改为所需的绘图即可。由于我没有我使用随机创建的 NumPy 数组的频谱图文件。您的实施无效,因为 fig, ax = plt.subplot(4,3,.....) 不适合使用。 Fig and axs returns in the function plt.subplots not plt.subplot.You 也可以使用该方法,但在for循环之外,然后访问axs元素。

最终代码为:

import matplotlib.pyplot as plt
import librosa
import librosa.display
import glob

path=glob.glob('E:/Python_On_All_Dataset/Four emotion_for plot/*.wav') 

fig, ax =  plt.subplots(nrows=4, ncols=3, sharex=True)

    
for i in range(4) :
   
    y, sr = librosa.load(path[i], sr=16000)
    librosa.display.waveplot(y, sr, ax=ax[i, 0])  # put wave in row i, column 0
    plt.axis('off')
    
    
   
    mfcc=librosa.feature.mfcc(y) 
    librosa.display.specshow(mfcc, x_axis='time', ax=ax[i, 1]) # mfcc in row i, column 1
   

    S = librosa.feature.melspectrogram(y, sr)
    librosa.display.specshow(librosa.power_to_db(S), x_axis='time', y_axis='log', ax=ax[i, 2])  # spectrogram in row i, column 2
   

尝试将此轴(在每个情节后关闭,但不知何故不起作用)