[R] Labelling a second y-axis

Marc Schwartz marc_schwartz at comcast.net
Thu Mar 22 03:09:02 CET 2007


On Wed, 2007-03-21 at 18:14 -0700, Jesse Sinclair wrote:
> Hi,
> I am using the following code as an example function to create  
> multiple y-axes on one plot. I have it working fine however, I can't  
> seem to add a label on the second (right) axis. I have tried adding  
> ylab="y2" in the axis call but, that didn't work; any ideas?
> 
> Thanks,
> 
> Jesse
> 
> Code:
> function() {
> 	par(las=1,xaxs="r",mai=c(1,0.75,1,1))
> 	x<-1:10
> 	y1<-x
> 	y2<-x^2
> 	plot(x,y1,xlim=c(0,10),ylim=c(0,10),ylab="y1")
> 	title(main="Multiple Y-Axes in R",ylab="y2")
> 	par(new=TRUE)
> 	plot(x,y2,xlim=c(0,10),xaxt="n",yaxt="n",ylab="",pch=16)
> 	axis(4,at=c(0,20,40,60,80,100))
> }

Normally, you would use mtext() to place text outside the plot region.

The problem is that mtext() does not support rotated text. Thus, we need
to use text() and adjust the 'srt' argument to rotate the text and
adjust the x and y axis values for placement. We also set the 'xpd'
argument so that the text is not clipped at the plot region.

        par(las=1,xaxs="r",mai=c(1,0.75,1,1))
        x<-1:10
        y1<-x
        y2<-x^2
        plot(x,y1,xlim=c(0,10),ylim=c(0,10), ylab="y1", las = 1)
        title(main="Multiple Y-Axes in R")

        par(new=TRUE)
        plot(x,y2,xlim=c(0,10),xaxt="n",yaxt="n",ylab="",pch=16)
        axis(4,at=c(0,20,40,60,80,100))

        text(12, 50, "y2", srt = 270, xpd = TRUE)

See ?text, ?par and ?mtext for more information.

HTH,

Marc Schwartz



More information about the R-help mailing list