# -*- coding: utf-8 -*-
from matplotlib import pyplotpyplot.rcParams['font.sans-serif'] = ['SimHei']
pyplot.rcParams['axes.unicode_minus'] = Falseimport numpy as np
import matplotlib.pyplot as pl
import matplotlib
import math
import randomN = 500 # 绘制点总数
fs = 5 # 正弦信号频率,即周期为0.2
n = [2 * math.pi * fs * t / N for t in range(N)] # 2πft/N 表示每个点的值
axis_x = np.linspace(0, 1, num=N) # 将0,1的区间分割成N个点
# myfont = matplotlib.font_manager.FontProperties(fname='c:\\windows\\fonts\\fzshjw_0.ttf')# 频率为5Hz的正弦信号
x = [math.sin(i) for i in n] # 计算每个点的正弦值
pl.subplot(221)
pl.plot(axis_x, x)
pl.title(u'5Hz的正弦信号')
pl.axis('tight')# 频率为5Hz、幅值为3的正弦+噪声x1 = [random.gauss(0, 0.5) for i in range(N)] # 给每个点随机生成高斯噪声,噪声值为0-0.5
xx = []
# 将噪声添加到信号中
for i in range(len(x)):xx.append(x[i] * 3 + x1[i])pl.subplot(222)
pl.plot(axis_x, xx)
pl.title(u'频率为5Hz、幅值为3的正弦+噪声')
pl.axis('tight')# 频谱绘制
xf = np.fft.fft(x) # fft变换
xf_abs = np.fft.fftshift(abs(xf))
axis_xf = np.linspace(-N / 2, N / 2 - 1, num=N)
pl.subplot(223)
pl.title(u'频率为5Hz的正弦频谱图')
pl.plot(axis_xf, xf_abs)
pl.axis('tight')# 频谱绘制
xf = np.fft.fft(xx)
xf_abs = np.fft.fftshift(abs(xf))
pl.subplot(224)
pl.title(u'频率为5Hz的正弦频谱图')
pl.plot(axis_xf, xf_abs)
pl.axis('tight')pl.show()