Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Created January 5, 2017 02:20
Show Gist options
  • Select an option

  • Save GaryLee/5c4bd8a86b35c6d3b07ee9695cf50ea4 to your computer and use it in GitHub Desktop.

Select an option

Save GaryLee/5c4bd8a86b35c6d3b07ee9695cf50ea4 to your computer and use it in GitHub Desktop.
A example to show how to plot spectrum for given signal.
# -*- coding: utf-8 -*-
"""
Plot spectrum of given signal.
"""
from numpy import sin, linspace, pi
from pylab import plot, show, title, xlabel, ylabel, subplot
from scipy import fft, arange
def plot_spectrum(y, freq_sampling):
"""
Plosampling_itvl a Single-Sided Amplitude Spectrum of y(t)
"""
n = len(y) # length of the signal
k = arange(n)
T = n / freq_sampling
frq = k/T # two sides frequency range
frq = frq[range(int(n/2))] # one side frequency range
Y = fft(y) / n # fft computing and normalization
Y = Y[range(int(n/2))]
plot(frq,abs(Y),'r') # plotting the spectrum
xlabel('Freq (Hz)')
ylabel('|Y(power)|')
freq_sampling = 150.0 # sampling rate
sampling_itvl = 1.0 / freq_sampling # sampling interval
t = arange(0, 1, sampling_itvl) # time vector
ff = 5 # frequency of the signal
y = sin(2 * pi * ff * t)
subplot(2, 1, 1)
plot(t, y)
xlabel('Time')
ylabel('Amplitude')
subplot(2, 1, 2)
plot_spectrum(y, freq_sampling)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment