效果图
纵坐标中的数据比较密集,不过不碍事,这个 GIF 主要想要说明程序运行效果。
源代码
程序应该很好理解,请忽略我设置的全局参数,这些不重要,程序逻辑很清楚。
import random
from math import pi, sin
import threading
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from scipy import signal
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
RANGE = 1000
START_Y = 0
END_Y = 1000
FREQUENCY = 10
KEY = 0
LastDistance = -1
Jitter_Threshold = 20
onlyonce = 0
fig = plt.figure()
ax = plt.axes(xlim=(0, RANGE), ylim=(0, RANGE))
ax.grid(axis='both')
x_ticks = np.arange(0, RANGE, 5*FREQUENCY)
y_ticks = np.arange(0, RANGE, 2*FREQUENCY)
plt.xticks(x_ticks)
plt.yticks(y_ticks)
x_line = [i for i in range(0, RANGE)]
y_line = [0.0 for i in range(0, RANGE)]
x_sin_line = [i for i in range(0, RANGE)]
y_sin_line = [0.0 for i in range(0, RANGE)]
x_square_line = [i for i in range(0, RANGE)]
y_square_line = [0.0 for i in range(0, RANGE)]
plt.ylim(bottom=START_Y, top=END_Y)
line, = plt.plot(x_line, y_line, linestyle='-', label='Real-time curve', linewidth=1, color='blue')
line_sin, = plt.plot(x_sin_line, y_sin_line, linestyle='-', label='', linewidth=1, color='red')
line_square, = plt.plot(x_square_line, y_square_line, linestyle='-', label='', linewidth=1, color='green')
text_ani = plt.text(900, 750, '', ha='center', va= 'bottom', fontsize=20)
sinx_g = None
square_wave_g = None
def draw():
def update(c):
x_line = [i for i in range(0, RANGE)]
distance = data_from_random()
y_line.pop(-1)
y_line.insert(0, distance)
line.set_data(x_line, y_line)
x_sin_line = [i for i in range(0, RANGE)]
y_sin_line.pop(-1)
y_sin_line.insert(0, sinx_g.__next__()[1])
line_sin.set_data(x_sin_line, y_sin_line)
x_square_line = [i for i in range(0, RANGE)]
y_square_line.pop(-1)
y_square_line.insert(0, square_wave_g.__next__()[1])
line_square.set_data(x_square_line, y_square_line)
text_ani.set_text("d= %.3f" % distance)
return line, line_sin, line_square, text_ani
anim = animation.FuncAnimation(fig=fig, func=update, interval=FREQUENCY, blit=True)
anim.save("text.gif", writer='pillow')
plt.show()
def data_from_square_wave(A=100, hz=20, h=0, step=1000):
"""
A: 振幅
hz:频率
h:位移高度
"""
t = 0
y = 0
while True:
y = signal.square(2 * np.pi * hz * t)
yield t, A*y + h
t += 1/step
def data_from_sinx(A=1, w=1, f=0, h=0, n=0, step=1000):
"""
@param A: 振幅
@param w: 频率 弧度制
@param f: 相位 弧度制
y = Asin(wx+f)
"""
x = -2*pi
while True:
x += 1/step
y = pow(A*sin(w*x + f) + h, n)
yield x, y
def data_from_random():
"""
返回[0, 500]间的随机整数
"""
return random.randint(0, 500)
if __name__ == "__main__":
sinx_g = data_from_sinx(A=50, w=4*pi, f=0, h=(START_Y+END_Y)/2+START_Y, n=1, step=1000)
square_wave_g = data_from_square_wave(A=100, hz=20, h=(START_Y+END_Y)/2+START_Y, step=1000)
threading.Thread(target=draw()).start()
|