如何用增加的局部极小值绘制点序列并用另一种颜色标记它们?与图片相似。我无法使用该顺序设置列表,并且最小值是错误的。还是有更简单的方法来做到这一点?

python - python-如何查找和视觉标记序列的局部最小值?-LMLPHP

我尝试了这段代码:

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()


我得到这个数字:

python - python-如何查找和视觉标记序列的局部最小值?-LMLPHP

最佳答案

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

find_peaks返回峰或最小值的索引。为了获得正确的绘图位置,必须使用x的输出索引seriesfind_peaks

如果您担心单个信号包含极小值递减的序列,则可以使用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()


python - python-如何查找和视觉标记序列的局部最小值?-LMLPHP

10-08 04:07