Skip to content

Instantly share code, notes, and snippets.

@superlou
Created February 18, 2013 14:30
Show Gist options
  • Save superlou/4977824 to your computer and use it in GitHub Desktop.
Save superlou/4977824 to your computer and use it in GitHub Desktop.
Check the units of the pyplot specgram to determine if the output is in terms of the original unit or unit-squared.
"""
Check the units of the pyplot specgram to determine if the
output is in terms of the original unit or unit-squared.
"""
import numpy as np
import matplotlib.pyplot as plt
def find_nearest(array, value):
idx = (np.abs(array - value)).argmin()
return (idx, array[idx])
Fs = 10000.0 # Hz
duration = 10 # seconds
t = np.arange(0, duration, 1 / Fs)
frequency = 100.0 # Hz
amplitude = 4.0 # volts
y = amplitude * np.sin(2 * np.pi * frequency * t)
plt.subplot(311)
plt.plot(t, y)
plt.subplot(312)
nfft = 8192
Pxx, freqs, bins, im = plt.specgram(y, Fs=Fs, NFFT=nfft, pad_to=nfft)
plt.ylim([0, 300])
plt.subplot(313)
index, nearest_freq = find_nearest(freqs, frequency)
print "Nearest frequency: " + str(nearest_freq)
plt.plot(bins, Pxx[index, :])
plt.ylim([0, 5])
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment