在Python中绘制正弦曲线的傅立叶变换 [英] Plotting Fourier Transform Of A Sinusoid In Python

查看:91
本文介绍了在Python中绘制正弦曲线的傅立叶变换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下python程序绘制正弦曲线:

 将matplotlib.pyplot导入为plt将numpy导入为np# 帆布plt.style.use("ggplot")#频率,振荡与幅度范围f = int(输入(输入频率:"))n_o = int(input(输入振荡次数:"))t_max = n_o/ft = np.linspace(0,t_max,1000)#正弦y_sin = np.sin(2 * np.pi * f * t)#在不同的轴上设置子图无花果,斧头= plt.subplots(2,1,constrained_layout = True)#正弦轴axs [0] .plot(t,y_sin,color ="firebrick",标签="sin({} Hz)".format(f))axs [0] .axhline(y = 0,颜色=灰色",线型=虚线",标签="y = 0")axs [0] .legend(loc =左下",frameon =真,fancybox =真,shadow = True,facecolor ="white")# 标题axs [0] .set_title("Sine")axs [0] .set_xlabel("Time(s)")axs [0] .set_ylabel("Amplitude")#轴限制axs [0] .axis([-0.05 * t_max,t_max + 0.05 * t_max,-1.5,1.5])plt.show() 

如何在第二个子图中绘制此频率的傅立叶变换?我见过各种示例,但它们仅适用于较小的频率,而我适用于100 Hz以上的频率.谢谢.

解决方案

通过正确应用

希望这会有所帮助.

The following python program plots a sinusoid:

import matplotlib.pyplot as plt
import numpy as np

# Canvas
plt.style.use("ggplot")

# Frequency, Oscillations & Range
f = int(input("Enter frequency: "))
n_o = int(input("Enter number of oscillations: "))
t_max = n_o/f
t = np.linspace(0, t_max, 1000)

# Sine
y_sin = np.sin(2*np.pi*f*t)

# Setting subplots on separate axes
fig, axs = plt.subplots(2, 1, constrained_layout = True)

# Sine axis
axs[0].plot(t, y_sin, color = "firebrick", label = "sin({}Hz)".format(f))
axs[0].axhline(y = 0, color = "grey", linestyle = "dashed", label = "y = 0")
axs[0].legend(loc = "lower left", frameon = True, fancybox = True,
              shadow = True, facecolor = "white")

# Title
axs[0].set_title("Sine")
axs[0].set_xlabel("Time(s)")
axs[0].set_ylabel("Amplitude")

# Axis Limits
axs[0].axis([-0.05*t_max, t_max+0.05*t_max, -1.5, 1.5])

plt.show()

How can i plot the Fourier transform of this frequency in the second subplot? I have seen various examples but they only work with small frequencies, whereas i'm working with frequencies above 100 Hz. Thanks.

解决方案

By correctly applying FFT on your signal you should be just fine:

# FFT
# number of samples
N = len(t)
# time step
dt = t[1]-t[0]
# max number of harmonic to display
H_max = 5

xf = np.linspace(0.0, 1.0/(2.0*dt), N//2)
yf = np.fft.fft(y_sin)

axs[1].plot(xf, (2/N)*np.abs(yf[:N//2]))
axs[1].set_xlim([0, H_max*f])
axs[1].set_xlabel('f (Hz)')
axs[1].set_ylabel('$||H_i||_2$')

which gives for inputs f=100 and n_o=3:

Hope this helps.

这篇关于在Python中绘制正弦曲线的傅立叶变换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆