pilogo
pilogo

Reputation: 85

How to plot librosa STFT output properly

I'm creating a sine wave of 100Hz and trying to plot it's stft :

import scipy.io
import numpy as np
import librosa
import librosa.display
#%matplotlib notebook
import matplotlib.pyplot as plt


A = 1                      # Amplitude
f0 = 100                     # frequency
Fs = f0 * 800                   # Sampling frequency
t = np.arange(Fs) / float(Fs)
X = np.sin(2*np.pi*t*f0)
plt.plot(t, X)
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.show()

D = np.abs(librosa.stft(X))
librosa.display.specshow(librosa.amplitude_to_db(D,ref=np.max),y_axis='log', x_axis='time')

STFT output

I was expecting a single line at 100Hz instead.

Also, how can I plot Frequency(X-axis) vs Amplitude(Y-axis) graph to see a peak at 100Hz?

Upvotes: 0

Views: 2768

Answers (1)

Jon Nordby
Jon Nordby

Reputation: 6289

You need to pass the sample rate to specshow, using the sr keyword argument. Otherwise it will default to 22kHz, which will give wrong results.

D = np.abs(librosa.stft(X))
db = librosa.amplitude_to_db(D,ref=np.max)
librosa.display.specshow(db, sr=Fs, y_axis='log', x_axis='time')

Upvotes: 2

Related Questions