2

I am working with audio using librosa, and I need to plot the spectrogram and waveform in the same display.

My code:

plt.figure(figsize=(14, 9))

plt.figure(1)

plt.subplot(211)
plt.title('Spectrogram')
librosa.display.specshow(stft_db, x_axis='time', y_axis='log')

plt.subplot(212)
plt.title('Audioform')
librosa.display.waveplot(y, sr=sr)

Using this code I get this plot

But I need something like this

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ari
  • 21
  • 1
  • 3

2 Answers2

2

According to librosa, you're able to provide the display methods with an axes to draw the item on, specshow, waveplot. I'd recommend defining your matplotlib figure and subplots outright, and then giving librosa the axes to plot them on.

fig = plt.figure(figsize=(14, 9)) #This setups the figure
ax1 = fig.subplots() #Creates the Axes object to display one of the plots
ax2 = ax1.twinx() #Creates a second Axes object that shares the x-axis

librosa.display.specshow(stft_db, x_axis='time', y_axis='log', ax=ax1)
librosa.display.waveplot(y, sr=sr, ax=ax2)
plt.show()

There might be some more formatting to be done to get the desired look, I'd recommend taking a look at this example from matplotlib, for a similar shared axes plot.

Joe Habel
  • 206
  • 1
  • 6
0

Instead of using subplots use the same axes of a single plot to display both the graphs.

fig = plt.figure(figsize=(14, 9))
ax = librosa.display.specshow(stft_db, x_axis='time', y_axis='log')
librosa.display.waveplot(y, sr=sr, ax=ax)
plt.show()
abhilb
  • 5,639
  • 2
  • 20
  • 26