Dirk Snyman
Dirk Snyman

Reputation: 47

Plotting intersections on line graphs in R

I want to use R to plot two data series with the same x-values (e.g. dates). I want the two lines on the same graph, but the segments where the one is larger than the other should be in another colour. So as an example:

x<-c(-5:5)
y1<-x^2-x-10
y2<-(x^3)-(x^2)-(10*x)+2
plot(x,y1,col="blue", ylim=c(-100,100), type="l")
par(new=T)
plot(x,y2,col="green", ylim=c(-100,100), type="l")

with the sections where y2 is larger than y1 to be red. Thus the green line would be red more or less where -3 < x < 1 and then again when x > 3 (I tried to post the figure but my reputation isn't high enough). I want to develop a bit of code that would allow me to do this for any set of data, for example in a matrix something like:

xy<-as.matrix(cbind(x,y1,y2))

I have a suspicion that it could be done using for and if loops, but I'd prefer a more elegant solution. If I could do something like this: Show the intersection of two curves as well, that would be great!

Thanks so much in advance for the help!

Upvotes: 2

Views: 351

Answers (1)

Carl Witthoft
Carl Witthoft

Reputation: 21502

Here's a very basic solution achieved by creating a couple new variables, with NA values to suppress plotting in the undesired regions:

y2high <- y2
y2high[y2high < y1] <- NA
y2low <- y2
y2low[y2low > y1] <- NA

plot(x,y1,type='l', col='blue')
lines(x,y2high,col='red')
lines(x,y2low,col='green')

Upvotes: 2

Related Questions