[R] plot with two y axes

Jim Lemon bitwrit at ozemail.com.au
Fri Sep 8 14:50:00 CEST 2000


Hi John,

As it happens, I once had the same problem myself.  I didn't have R
then, but it was kind of fun seeing how much easier it is.  You will
probably want to dress this up a bit as it is very basic.

Jim


-------------- next part --------------
plot2ax<-function(x1,y1,xlim1,ylim1,x2,y2,xlim2,ylim2,y2lab=NULL,type="b",pch1=1,pch2=2,...) {
 if(!missing(y1)) {
  oldmar<-par("mar")
  par(mar=c(5,4,4,4))
  if(missing(x1)) x1<-1:length(y1)
  if(missing(xlim1)) xlim1<-range(x1)
  if(missing(ylim1)) ylim1<-range(y1)
  plot(x1,y1,xlim=xlim1,ylim=ylim1,pch=pch1,...)
  if(!missing(y2)) {
   if(missing(x2)) x2<-1:length(y2)
   if(missing(xlim2)) xlim2<-range(x2)
   if(missing(ylim2)) ylim2<-range(y2)
   ax2inc<-(ylim2[2] - ylim2[1])/6
   ax2val<-c(ylim2[1],ylim2[1]+ax2inc,ylim2[1]+2*ax2inc,ylim2[1]+3*ax2inc,
    ylim2[2]-2*ax2inc,ylim2[2]-ax2inc,ylim2[2])
   axis(4,labels=as.character(ax2val))
   xmult<-(xlim1[2] - xlim1[1])/(xlim2[2] - xlim2[1])
   ymult<-(ylim1[2] - ylim1[1])/(ylim2[2] - ylim2[1])
   points((x2-xlim2[1])*xmult+xlim1[1],(y2-ylim2[1])*ymult+ylim1[1],pch=pch2)
   mtext(y2lab,4,2)
  }
  par(oldmar)
 }
 else cat("Usage: plot2ax(x1,y1,xlim1,ylim1,x2,y2,xlim2,ylim2,y2lab,type=\"b\",pch1=1,pch2=2)\n")
}


More information about the R-help mailing list