0

I am trying to do the following:

  • plot a time series in R using a polygonal line
  • plot one or more horizontal lines superimposed
  • find the intersections of said line with the orizontal ones

I got this far:

set.seed(34398)
c1 <- as.ts(rbeta(25, 33, 12)) 
p <- plot(c1, type = 'l')
# set thresholds
thresholds <- c(0.7, 0.77)

I can find no way to access the segment line object plotted by R. I really really really would like to do this with base graphics, while realizing that probably there's a ggplot2 concoction out there that would work. Any idea?

abline(h=thresholds, lwd=1, lty=3, col="dark grey")
zx485
  • 28,498
  • 28
  • 50
  • 59
lambda_vu
  • 207
  • 1
  • 2
  • 5
  • 2
    Did you try [this](http://stackoverflow.com/questions/20519431/finding-point-of-intersection-in-r) ? – Haboryme Jan 29 '17 at 12:14
  • 4
    Dont think of it as a graphics problem. The "segment line object" is just the data from your time series object, linearly interpolated. – Spacedman Jan 29 '17 at 12:17
  • you are of course correct. I thought there was a way to access the results of the computation that lead R to draw that linear interpolation, but G5w's answer below is good enough for my purposes. Thank you for your contribution. – lambda_vu Jan 29 '17 at 18:35

1 Answers1

1

I will just do one threshold. You can loop through the list to get all of them. First find the points, x, so that the curve crosses the threshold between x and x+1

shift = (c1 - 0.7)
Lower = which(shift[-1]*shift[-length(shift)] < 0)

Find the actual points of crossing, by finding the roots of Series - 0.7 and plot

shiftedF = approxfun(1:length(c1), c1-0.7)
Intersections = sapply(Lower, function(x) { uniroot(shiftedF, x:(x+1))$root })
points(Intersections, rep(0.7, length(Intersections)), pch=16, col="red")

Crossing the threshold

G5W
  • 36,531
  • 10
  • 47
  • 80
  • Thank you. I didn't know about approxfun, but i imagined the solution would involve shifting the polyline down – lambda_vu Jan 29 '17 at 18:27