Skip to content

Instantly share code, notes, and snippets.

@kylerbrown
Last active January 7, 2019 08:14
Show Gist options
  • Save kylerbrown/d0394a87e443889f8b8917b80fc63ec3 to your computer and use it in GitHub Desktop.
Save kylerbrown/d0394a87e443889f8b8917b80fc63ec3 to your computer and use it in GitHub Desktop.
Python code for creating zebra finch spectrograms
# Looking for a decent spectrogram? Check out resin.
#
# https://github.com/kylerbrown/resin
#
# Resin creates multi-taper spectrograms and spectral derivative spectrograms
#
# old code below...
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def spectrogram(data, sr, start, stop, ms_nfft=10,
ax=None, osc=True, cmap=cm.inferno, **kwargs):
"""
data : a vector of samples, first sample starts at time = 0
sr : sampling rate
start : start time to slice data, units: seconds
stop : stop time to slice data, units: seconds
ms_nfft : width of fourier transform in milliseconds
decent colormaps: cm.viridis, cm.inferno, cm.magma, cm.plasma
extra arguments are sent to plt.specgram
"""
nfft = int(ms_nfft / 1000. * sr)
start_samp = int(start*sr) - nfft//2
stop_samp = int(stop*sr) - nfft//2
x = data[start_samp:stop_samp]
if ax is None:
ax = plt.gca()
plt.sca(ax)
plt.specgram(x, Fs=sr, NFFT=nfft, noverlap=nfft-(int(sr*.001)), cmap=cmap, **kwargs)
if osc:
plt.plot(np.arange(len(x))/sr, data[int(start*sr):int(stop*sr)]/np.max(x)*1000+6000)
plt.ylim(300, 8000)
@rudrathegreat
Copy link

Just wondering, why are you using plt.specgram instead of scipy.signal.spectrogram?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment