[R] Legend and Main Title positioning

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Fri Dec 5 14:43:30 CET 2008


> layout(matrix(c(1,2,3,4), nrow = 2, byrow = TRUE))
> plot(rnorm(100))
> plot(rnorm(200))
> plot(rnorm(300))
> plot(rnorm(400))
> 
> Now, I'd like to create a legend below each plot and generate a common 
title.
> How can I do that?

If you are laying plots out in grids like this then lattice graphics are 
generally the way to go, but here's a solution based upon base graphics. 
The trick is to include extra potting space in your layout for the 
legends.  The code is messy, since it requires you to manually specify 
which cell of the layout to plot into, but I'm sure guven some thought you 
can automate this.

#4 space for plots, 4 for legends
layout(matrix(1:8, nrow = 4, byrow = TRUE), heights=rep(c(3,1),4))

#Check the layout looks suitable
layout.show(8)

#Avoid clipping problems, and create space for your title
par(xpd=TRUE, oma=c(0,0,2,0))

#First plot
plot(rnorm(100))

#Move down and plot the first legend
par(mfg=c(2,1))
legend(0,0, legend="foo", pch=1)

#Repeat for the other plots and legends
par(mfg=c(1,2))
plot(rnorm(200))
par(mfg=c(2,2))
legend(0,0, legend="bar", pch=1)

par(mfg=c(3,1))
plot(rnorm(300))
par(mfg=c(4,1))
legend(0,0, legend="baz", pch=1)

par(mfg=c(3,2))
plot(rnorm(400))
par(mfg=c(4,2))
legend(0,0, legend="quux", pch=1)

#Title for all the plots
title(main="4 plots", outer=TRUE)


Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}



More information about the R-help mailing list