Search code examples
rplotgraphicstimeserieschart

Access lines plotted by R using basic plot()


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

Solution

  • 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