Search code examples
matplotlibsubplot

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


I have a folder containing multiple wav files (currently say 4). I want to plot the wav, its mfcc and mel spectrogram in a row , so finally a figure with 12 plots(each row with three figure, and hence four rows). I am not able to plot the graph, only extracted the features. Can some one help with this for loop please. I mean how to use subplot command and how to store each figure in loop.

Regards

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()

Solution

  • The final code is :

    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
       
    

    Tried putting this axis(off after every plot, but somehow its not working)

    enter image description here