[R] How to plot? stack line plot with different Y axis

Jim Lemon jim at bitwrit.com.au
Mon Mar 17 09:12:24 CET 2014


On 03/17/2014 05:07 PM, Jinsong Zhao wrote:
> Hi there,
>
> I just find a fancy plot like the following:
>
> http://www.nature.com/nature/journal/v505/n7481/images_article/nature12784-f2.jpg
>
>
> I am wondering how to plot something like that in R. Which package will
> be convenient for doing such things.
>
> BTW, the link that points to R graph gallery
> (http://addictedtor.free.fr/graphiques) provided by wiki seems break.
>
Hi Jinsong,
This is possible, but takes a bit of work. First start a graphics device 
of about the correct ratio:

layout(matrix(1:2,ncol=1),heights=c(1,3))

adjust the margins for the top plot and display it:

par(mar=c(2,4,4,4))
plot(c(2000,3800,4100),c(17.5,16.5,15),type="b",
  xlim=c(-100,4000),ylim=c(14,18),
  lwd=2,pch=3,col=4,xaxt="n",xlab="",ylab="Ylab")
mtext("Year before AD 1950",side=3,line=2.5,cex=1.2,font=2)
lines(c(400,2510,3400,4100),c(16.2,15.8,15.5,14.3),type="b",pch=3,col=2)
axis(3,at=seq(0,4000,by=500),labels=seq(4000,0,by=-500))

then set the margins for the bottom plot:

par(mar=c(5,4,0,4))

plot the first series, leaving enough space with "ylim" for the rest:

dust<-runif(1201,-2,2)
plot(800:2000,dust,type="l",ylim=c(-2,12),yaxt="n",
  ylab="",xlab="Year AD",lwd=2,col="lightgreen")

After the first plot, you can add series of lines to the plot using the 
lines or points functions. You will have to add a constant amount to the 
y values to get them spaced out vertically and calculate the correct 
position and spacing when you are adding the different y axes. Use 
"mtext" to add the labels and "expression" to get the mathematical and 
other symbols. Good luck with it.

Jim




More information about the R-help mailing list