add a curve that fits the peaks from a plot in R?

强颜欢笑 提交于 2019-12-19 04:56:47

问题


Is there a function that adds a curve that fits the peaks if given two vectors and their plot? For example, I have:

x= c(0:20)

x [1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

y [1] 19.4 17.9 8.1 11.3 7.8 8.0 5.0 1.7 3.9 5.4 7.5 5.4 4.7 5.0 4.9 3.5 2.9 2.4 1.4 1.7

plot(x,y,xlim=range(x),ylim=range(y))

best, Nanami


回答1:


Mathematically speaking, your problem is very poorly defined. You supply a range of discrete values, not a function, for your y values. This means it can not be differentiated to find local maxima.

That said, here is a bit of code that might get you started. It makes use of a function called peaks, (attributed to Brian Ripley):

peaks<-function(series,span=3){
  z <- embed(series, span)
  s <- span%/%2
  v<- max.col(z) == 1 + s
  result <- c(rep(FALSE,s),v)
  result <- result[1:(length(result)-s)]
  result
} 

x <- c(1:20)
y <- c(19.4, 17.9, 8.1, 11.3, 7.8, 8.0, 5.0, 1.7, 3.9, 
       5.4, 7.5, 5.4, 4.7, 5.0, 4.9, 3.5, 2.9, 2.4, 1.4, 1.7)

plot(x,y, type="l")
p <- which(peaks(y, span=3))

lines(x[p], y[p], col="red", type="b)

The problem is that the concept of local peaks is poorly defined. How local do you mean? The peaks algorithm as supplied allows you to modify the span. Have a play and see whether it is helpful at all.



来源:https://stackoverflow.com/questions/6324354/add-a-curve-that-fits-the-peaks-from-a-plot-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!