Multiple Y-axis in a R plot

[This article was first published on EvolvingSpaces, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I often have to to plot multiple time-series with different scale of values for comparative purposes, and although placing them in different rows are useful, placing on a same graph is still useful sometimes…
I searched a bit about this, and found some nice suggestions for 2 Y-axis, but haven’t found anything for more 2+. So here’s my solution:

#Create Dataset


#Define Margins. The trick is to use give as much space possible on the left margin (second value)
par(mar=c(5, 12, 4, 4) + 0.1)

#Plot the first time series. Notice that you don’t have to draw the axis nor the labels

plot(time, pop, axes=F, ylim=c(0,max(pop)), xlab=””, ylab=””,type=”l”,col=”black”, main=””,xlim=c(7000,3400))
axis(2, ylim=c(0,max(pop)),col=”black”,lwd=2)

#Plot the second time series. The command par(new=T) is handy here. If you just need to plot two timeseries, you could also use the right vertical axis as well. In that case you have to substitute “2” with “4” in the functions axis() and mtext(). Notice that in both functions lines is increased so that the new axis and its label is placed to the left of the first one. You don’t need to increase the value if you use the right vertical axis.

plot(time, med, axes=F, ylim=c(0,max(med)), xlab=””, ylab=””, 
type=”l”,lty=2, main=””,xlim=c(7000,3400),lwd=2)
axis(2, ylim=c(0,max(med)),lwd=2,line=3.5)
points(time, med,pch=20)
mtext(2,text=”Median Group Size”,line=5.5)

#Plot the third time series. Again the line parameter are both further increased.

plot(time, grp, axes=F, ylim=c(0,max(grp)), xlab=””, ylab=””, 
type=”l”,lty=3, main=””,xlim=c(7000,3400),lwd=2)
axis(2, ylim=c(0,max(grp)),lwd=2,line=7)

points(time, grp,pch=20)
mtext(2,text=”Number of Groups”,line=9)

#We can now draw the X-axis, which is of course shared by all the three time-series.

mtext(“cal BP”,side=1,col=”black”,line=2)

#And then plot the legend.

legend(x=7000,y=12,legend=c(“Population”,”Median Group Size”,”Number of Groups”),lty=c(1,2,3))

To leave a comment for the author, please follow the link and comment on their blog: EvolvingSpaces. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)