A blog by Rob J Hyndman 

Twitter Gplus RSS

R graph with two y-​​axes

Published on 5 February 2008

I’ve been asked how to do this sev­eral times, so I thought it might help to put an exam­ple online.

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"))



Related Posts:


 
Tags:
16 Comments  comments 
  • Logan

    Thank you very much for post­ing this code. It was exactly what I needed.

  • Duleep Kumar Samuel

    Thank you so much, lovely graph

  • Julius Sum­i­har

    Hey, thanks a lot for mak­ing this exam­ple online. It has helped me! Thanks!!

  • Bev­erly Schnell

    Thank you very much.
    This was very helpful.

  • http://flyordie.sin.khk.be kmelis

    Those are not axes, those are just lines.
    It is help­ful though, for plot­ting dif­fer­ent plots on top of eachother.

  • basem

    thank you very much; it was very help­ful for me

  • Tim

    Thanks,
    what I was look­ing for!

  • ola

    Very help­ful.

  • Khaya

    Very help­ful

  • ana

    Thanks, very help­ful for me too

  • mario

    what if x1=1:5 and x2=3:7? how to plot this? when I try the same exam­ple above, then R fits both time-​​series on top of each other rather than lagged..

    • http://robjhyndman.com Rob J Hyndman

      My exam­ple does not involve time series, so I don’t know what you mean. If you change the x val­ues in the sec­ond plot, then you will won’t get any­thing use­ful. If you want to plot time series, than make ts objects first.

    • Isaac Miyakawa

      To Mario:
      Use xlim 1 to 7 in each plot().

  • Shon

    Thank you so helpful..

  • Guest

    Great! Thanx.

  • RM

    Thanks a lot. This is very useful