Two y-axes with mfrow() or layout()

If you need to have two y-axes, the solution is to use a combination of axis() and mtext(). For example:

x <- 1:5
y1 <- rnorm(5)
y2 <- rnorm(5,20)
par(mar=c(5,4,4,5)+.1)
plot(x,y1,type="l",col="red")
par(new=TRUE)
plot(x, y2,,type="l",col="blue",xaxt="n",yaxt="n",xlab="",ylab="")
axis(4)
mtext("y2",side=4,line=3)
legend("topleft",col=c("red","blue"),lty=1,legend=c("The variable y1","The variable y2"))

But if you want have several plots in the same graphs, using layout() or mfrow(), a problem occurs because the size of the second y-axe is not the same as the size of the first:

layout(matrix(1:4, ncol=2))
x <- 1:5
y1 <- rnorm(5)
par(mar=c(5,4,4,5)+.1)
plot(x,y1,type="l",col="red", ylab="Variable y1")
axis(4)
mtext("Variable y2",side=4,line=3)

The problem occurs because cex parameter for mtext is an absolut value and it does not use par("cex"). The solution is to force the use of par("cex"):

layout(matrix(1:4, ncol=2))
x <- 1:5
y1 <- rnorm(5)
par(mar=c(5,4,4,5)+.1)
plot(x,y1,type="l",col="red", ylab="Variable y1")
axis(4)
mtext("Variable y2",side=4,line=3, cex=par("cex"))


Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04