Search code examples
rplotlabelapache-axisaxis-labels

R: how to rotate label of secondary Y axis?? {base}


I've created secondary Y axis, and I've put a label there as well using mtext. However, I can't figure out how to rotate my secondary Y label in the way to face a plot - like my red Y2 label ?

My dummy data, adopted from : http://robjhyndman.com/hyndsight/r-graph-with-two-y-axes/

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("y1","y2"))

result:

enter image description here

I've tried srt = ..., of las = ..., neither of them does work.

I don't necessary need to use mtext, is there please another simple solution ?

Thank you !


Solution

  • Use text instead of mtext:

    set.seed(1)
    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)
    text(par("usr")[2]*1.11,mean(par("usr")[3:4]), "y2", srt = -90, xpd = TRUE, pos = 4)
    legend("topleft",col=c("red","blue"),lty=1,legend=c("y1","y2"))
    

    (via)

    enter image description here