Basj
Basj

Reputation: 46443

2D plot of a matrix with colors like in a spectrogram

How to plot, with Python, a 2D matrix A[i,j] like this:

Is there a Python function for that?

(NB: I don't want a function that does the spectrogram for me, such as specgram, because I want to compute the FFT of the signal myself; thus I only need a function that plots a matrix with colors)

Spectrogram sample

Upvotes: 4

Views: 16193

Answers (1)

Basj
Basj

Reputation: 46443

Let Z be the array, here is what I finally use:

plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
           vmin=-100, vmax=0, origin='lowest', aspect='auto')
plt.colorbar()
plt.show()

Notes:

  • 'jet' is the colormap that is seen in the question's image, see also these colormaps

  • setting origin='lowest' has the same effect than replacing np.transpose(Z) by np.transpose(Z)[::-1,]

  • vmin, vmax give the scale (here from 0 to -100 dB in the example)

  • extent gives the limits of the x-axis (here 0 to 4.2 seconds) and y-axis (0 to 48000 Hz) (in this example I'm plotting the spectrogram of a 4.2 second-long audio file of samplerate 96Khz)

  • if aspect='auto' is not set, the plot would be very thin and very high (due to 4.2 vs. 48000 !)

Upvotes: 10

Related Questions