The following Python code uses numpy to produce a frequency plot of a sinusoid graph :
JavaScript
x
17
17
1
import numpy as np
2
import matplotlib.pyplot as plt
3
import scipy.fftpack
4
5
# Number of samplepoints
6
N = 600
7
# sample spacing
8
T = 1.0 / 800.0
9
x = np.linspace(0.0, N*T, N)
10
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
11
yf = scipy.fftpack.fft(y)
12
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
13
14
fig, ax = plt.subplots()
15
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
16
plt.show()
17
Based on the code above , we are plotting a sine wave with two frequencies, one at 50Hz and another at 80 Hz. You can clearly see the Fourier transform plot shows peaks at those two frequencies.
My question: How do I modify the above code so that the x-axis ranges from 0-100Hz ?
If I change
JavaScript
1
2
1
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
2
to
JavaScript
1
2
1
xf = np.linspace(0.0, 100, N//2)
2
Then my graph looks like:
But the graph now shows my peaks at around 11 and 20Hz, which is not correct. When I change my axis, the peak values should not change.
What am I doing wrong?
Advertisement
Answer
JavaScript
1
20
20
1
import numpy as np
2
import matplotlib.pyplot as plt
3
import scipy.fftpack
4
5
# Number of samplepoints
6
N = 600
7
# sample spacing
8
T = 1.0 / 800.0
9
x = np.linspace(0.0, N*T, N)
10
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
11
yf = scipy.fftpack.fft(y)
12
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
13
14
fig, ax = plt.subplots()
15
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
16
ax.set(
17
xlim=(0, 100)
18
)
19
plt.show()
20
simply add the xlim