2

What I'm looking for is best explained by a picture: A line that "contours" the maxima of my points (like giving the "skyline" of the plot). I have a plot of scattered points with dense, (mostly) unique x coordinates (not equally distributed in either axis). I want a red line surfacing this plot:

a plot that contours the maximas of a plot

What I've tried/thought of so far is, that a simple "draw as line" approach fails due to the dense nature of the data with unique x values and a lot of local maxima and minima (basically at every point). The same fact makes a mere "get maximum"-approach impossible.

Therefore I'm asking: Is there some kind of smoothing option for a plot? Or any existing "skyline" operator for a plot?

I am specifically NOT looking for a "contour plot" or a "skyline plot" (as in Bayesian skylineplot) - the terms would actually describe what I want, but unfortunately are already used for other things.

Here is a minimal version of what I'm working with so far, a negative example of lines not giving the desired results. I uploaded sample data here.

load("xy_lidarProfiles.RData")
plot(x, y, 
          xlab="x", ylab="y", # axis
          pch = 20, # point marker style (1 - 20)
          asp = 1 # aspect of x and y ratio
)
lines(x, y, type="l", col = "red") # makes a mess

this is not what I want but get when using R lines

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Honeybear
  • 2,928
  • 2
  • 28
  • 47

1 Answers1

1

You will get close to your desired result if you order() by x values. What you want then is a running maximum, which TTR::runMax() provides.

plot(x[order(x)], y[order(x)], pch=20)
lines(x[order(x)], TTR::runMax(y[order(x)], n=10), col="red", lwd=2)

enter image description here

You may adjust the window with the n= parameter.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • Nice solution. More generally, if the local max isn't what you want (e.g. it's not smooth enough), the `zoo::rollapply` function can find other local envelopes. – user2554330 Feb 17 '21 at 11:06