user3805148
user3805148

Reputation: 37

Plotting spectrum of a signal

from numpy.fft import fft
from numpy import array
a = array([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
print( ' '.join("%5.3f" % abs(f) for f in fft(a)) )

I am using this code to get fft of a signal but how can I plot the fft. Thanks

Upvotes: 0

Views: 1161

Answers (1)

Roland Smith
Roland Smith

Reputation: 43505

Here is an example I wrote to plot a wav file. It is slightly more complicated because it deals with a stereo sound file by averaging the left and right channels. And it plots both the signal and the fft.

from __future__ import print_function, division
import wave
import numpy as np
import matplotlib.pyplot as plt

wr = wave.open('input.wav', 'r')
sz = wr.getframerate()
q = 5  # time window to analyze in seconds
c = 12  # number of time windows to process
sf = 1.5  # signal scale factor

for num in range(c):
    print('Processing from {} to {} s'.format(num*q, (num+1)*q))
    avgf = np.zeros(int(sz/2+1))
    snd = np.array([])
    # The sound signal for q seconds is concatenated. The fft over that
    # period is averaged to average out noise.
    for j in range(q):
        da = np.fromstring(wr.readframes(sz), dtype=np.int16)
        left, right = da[0::2]*sf, da[1::2]*sf
        lf, rf = abs(np.fft.rfft(left)), abs(np.fft.rfft(right))
        snd = np.concatenate((snd, (left+right)/2))
        avgf += (lf+rf)/2
    avgf /= q
    # Plot both the signal and frequencies.
    plt.figure(1)
    a = plt.subplot(211)  # signal
    r = 2**16/2
    a.set_ylim([-r, r])
    a.set_xlabel('time [s]')
    a.set_ylabel('signal [-]')
    x = np.arange(44100*q)/44100
    plt.plot(x, snd)
    b = plt.subplot(212)  # frequencies
    b.set_xscale('log')
    b.set_xlabel('frequency [Hz]')
    b.set_ylabel('|amplitude|')
    plt.plot(abs(avgf))
    plt.savefig('simple{:02d}.png'.format(num))
    plt.clf()

Below is one of the plots it generated. Colours et cetera are different from the default because of my custom matplotlibrc.

Sample output image of fft plot script

Upvotes: 4

Related Questions