gpt4 book ai didi

python - 如何找到并直观地标记序列的局部最小值?

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:58 24 4
gpt4 key购买 nike

如何绘制一系列具有递增局部最小值的点并用另一种颜色标记它们?类似于图片中的东西。我无法设置具有该序列的列表,并且最小值是错误的。或者有更简单的方法吗?

example of a plot

我试过这段代码:

import sys
from numpy import NaN, Inf, arange, isscalar, asarray, array
import random
import numpy as np
import matplotlib.pyplot as plt

def peakdet(v, delta, x = None):
'''
Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x)
'''
maxtab = []
mintab = []

if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')

mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx-delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn+delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab)

if __name__=="__main__":
from matplotlib.pyplot import plot, scatter, show
series = [7,6,5,4,3,1,3,5,6,9,12,13,10,8,6,3,5,6,7,8,13,15,11,12,9,6,4,8,9,10,15,16,17,19,22,17,15,13,11,10,7,5,8,9,12]
maxtab, mintab = peakdet(series,.3)
y = np.linspace(0, 10, len(series))
plt.plot(y, series, '-', color='black');
# scatter(array(maxtab)[:,0], array(maxtab)[:,1], color='blue')
scatter(array(mintab)[:,0], array(mintab)[:,1], color='red')
show()

我得到了这个数字:

the resulting plot

最佳答案

尝试 scipy.signal.find_peaks .要找到最小值,您需要将 series 乘以 -1。

find_peaks 返回峰值或最小值的索引。要获得正确的绘图位置,您必须使用 find_peaks 的输出索引 xseries

如果您担心您的信号包含递减最小值序列,您可以使用 np.diff 比较连续峰值的大小。

import matplotlib.pyplot as plt
from scipy.signal import find_peaks
import numpy as np

series = np.array([7,6,5,4,3,1,3,5,6,9,12,13,10,8,6,3,5,6,7,8,13,15,11,12,9,6,4,8,9,10,15,16,17,19,22,17,15,13,11,10,7,5,8,9,12])
peaks, _ = find_peaks(series)
mins, _ =find_peaks(series*-1)
x = np.linspace(0, 10, len(series))
plt.plot(x, series, color='black');
plt.plot(x[mins], series[mins], 'x', label='mins')
plt.plot(x[peaks], series[peaks], '*', label='peaks')
plt.legend()

enter image description here

关于python - 如何找到并直观地标记序列的局部最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com