2

so I found the following code that spits out a spectrogram. However, i'd like to add some random colours to it via colormap or other methods. I've read the cmap documentation and didn't understand a thing.

The code:

import matplotlib.pyplot as plt
from scipy.io import wavfile

def graph_spectrogram(wav_file):
    rate, data = get_wav_info(wav_file)
    nfft = 256  
    fs = 256    
    pxx, freqs, bins, im = plt.specgram(data, nfft,fs)
    plt.axis('off')
    plt.savefig('sp_xyz.png',
                dpi=100, # Dots per inch
                frameon='false',
                aspect='normal',
                bbox_inches='tight',
                pad_inches=0) 
    plt.show()

def get_wav_info(wav_file):
    rate, data = wavfile.read(wav_file)
    return rate, data

if __name__ == '__main__': # Main function
    wav_file = 'song.wav' 
    graph_spectrogram(wav_file)

Thanks in advance for your help!

song
  • 83
  • 2
  • 7

1 Answers1

3

You can add a cmap argument in your specgram command itself. See the specgram docs. You can select a colourmap that suits you from the Colormaps reference. An example command would be:

pxx, freqs, bins, im = plt.specgram(data, nfft, fs, cmap='plasma')

If needed, you can also add a colorbar to the side, showing what each colour means.

VBB
  • 1,305
  • 7
  • 17