from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
data_x = np.arange(start = 0, stop = 40, step = 1, dtype='int')
data_y = np.array([98,96,97,100,95,105,75,50,45,42,
51,85,90,92,91,89,101,62,65,52,
47,58,55,75,89,92,94,91,89,79,
85,65,42,55,48,50,85,88,95,100])
# Find peaks
# order:两侧使用多少点进行比较
peak_indexes = signal.argrelextrema(data_y, np.greater, order=1)
peak_indexes = peak_indexes[0]
# Find valleys
# order:两侧使用多少点进行比较
valley_indexes = signal.argrelextrema(data_y, np.less, order=1)
valley_indexes = valley_indexes[0]
(fig, ax) = plt.subplots()
# Plot all data
ax.plot(data_x, data_y)
# Plot peaks
peak_x = peak_indexes
peak_y = data_y[peak_indexes]
ax.scatter(peak_x, peak_y, marker='o', color='red', label="Peaks")
# Plot valleys
valley_x = valley_indexes
valley_y = data_y[valley_indexes]
ax.scatter(valley_x, valley_y, marker='o', color='green', label="Valleys")
# 添加标题
plt.title('Find peaks and valleys using argrelextrema()')
# 添加图例
plt.legend(loc='best')
# 保存图像
plt.savefig('peaks-valleys.png')
# 显示图像
plt.show()
设置order = 1,运行结果:
设置order = 3,运行结果: