How to plot, with Python, a 2D matrix A[i,j]
like this:
i
is the x-axisj
is the y-axisA[i,j]
is a value between 0 and 100 that has to be drawn by a colour (ex: 0=blue, 100=red)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)
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 !)