Reputation: 809
I'm pretty new to Pyplot and I'm trying to plot the Raw wave of an audio file together with its spectrogram. I have written the following code and received the result shown in the screenshot below (code is slightly abbreviated for readability):
fig = plt.figure(figsize=(14, 8))
sample_rate, audio = ... # rate and wave data loaded with scipy.io.wavfile.read
show_wave(audio, sample_rate, fig)
freqs, times, spec = ... # spectrogram created with scipy.signal.spectrogram
show_spectrogram(freqs, times, spec, fig)
def show_wave(audio, sample_rate, fig):
ax1 = fig.add_subplot(211)
title = ... # some title created dynamically
ax1.set_title(title)
ax1.set_ylabel('Amplitude')
ax1.set_xlabel('Audio frames')
ax1.plot(np.linspace(0, len(audio), len(audio)), audio)
return ax1
def show_spectrogram(freqs, times, spec, fig):
ax2 = fig.add_subplot(212)
extent = [times.min(), times.max(), freqs.min(), freqs.max()]
ax2.imshow(spec.T, aspect='auto', origin='lower', extent=extent)
ax2.set_yticks(freqs[::16])
ax2.set_xticks(times[::int(len(times)/10)])
ax2.set_title(...) # some title created dynamically
ax2.set_ylabel('Freqs in Hz')
ax2.set_xlabel('Seconds')
return ax2, extent
I want to display both plots stacked so I can compare the raw wave with its spectrogram. However, the plot created with ax1.plot(...)
seems to add some padding to the left and the right of the data points (the zero-tick is not at the origin of the axes, data points do not span the whole available area) whereas the plot created with ax2.imshow
does not do this (plots spans the whole area).
How can I remove the "padding" in ax1.plot
so that the data points from the raw wave and the spectrogram are vertically aligned and comparable?
Upvotes: 1
Views: 347
Reputation: 339380
Solution of OP edited out of question:
As Julien Marrec pointed out below the solution is simple: add the following line in show_wave
and show_spectrogram
and it worked perfectly...
def show_wave(...)
...
ax1 = fig.add_subplot(211)
ax1.set_xlim(0, len(audio))
...
def show_spectrogram(...)
...
ax2 = fig.add_subplot(212)
ax2.set_xlim(0, times.max())
...
Upvotes: 0
Reputation: 11905
Use ax1.set_xlim(0, len(audio))
to force the boundaries of the xaxis to go from 0 to len(audio)
which is what your data actually spans, that will eliminate the "padding" you see.
Upvotes: 1