2

How can I plot a second line in a XY-plot, using plot(), to a different scale like this example (purple line)?

enter image description here

My R code for the first (red) line is something like:

p <- sqlQuery(ch,"SELECT wl,param1 FROM qryPlot ORDER BY wl")
plot(p$wl,p$param1,axes=T,xlim=c(400,800),ylim=c(0,100),type="l",col="red")
waanders
  • 8,907
  • 22
  • 70
  • 102
  • I think this has been addressed before too. Let me try to find the other Q/As... – John Colby Feb 06 '12 at 16:09
  • 3
    http://stackoverflow.com/questions/5479822/plotting-4-curves-in-a-single-plot-with-3-y-axes-in-r http://stackoverflow.com/questions/6142944/how-can-i-plot-with-2-different-y-axes-in-r – John Colby Feb 06 '12 at 16:11
  • http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-create-a-plot-with-two-y_002daxes_003f (googling "r faq two y axes" is also useful) – Ben Bolker Feb 06 '12 at 16:40
  • The R-FAQ is distributed with R. On my device it is part of the help functionality, but it will also be the first hit on a google search for R FAQ .... the google people like R. – IRTFM Feb 06 '12 at 16:41
  • @DWin Sure, but I meant where in the R FAQ? But Ben Bolker already already answered. Thank you both – waanders Feb 06 '12 at 16:52
  • 2
    It's not *that* hard to search the FAQ for "two y-axes", is it ... ? – Ben Bolker Feb 06 '12 at 17:04
  • http://stackoverflow.com/questions/5479822/ = about another situation: 4 different plots in 1 graph. http://stackoverflow.com/questions/6142944 is ok but not accomplished with plot() function – waanders Feb 06 '12 at 18:37

2 Answers2

9

Here is the general idea:

plot(1:10)
par(new=T)
plot(1:10, rep(50, 10), type='l', axes=F, xlab=NA, ylab=NA)
axis(4)

enter image description here

John Colby
  • 22,169
  • 4
  • 57
  • 69
1

I slightly extended the answer by @johncolby to this:

x<-1:20
y1<-sqrt(x)
y2<-sqrt(x)*x
plot(x,y1,ylim=c(0,25),col="blue")
par(new=TRUE)
plot(x,y2,ylim=c(0,100),col="red",axes=FALSE)
axis(4)

(axes=FALSE in second plot() command = to prevent labels second axis printed on the left side)

With this result:

enter image description here

Little problem to solve: labels both y-axes are printed to the left side.

waanders
  • 8,907
  • 22
  • 70
  • 102