Using the par(mfrow = c(m,n))
command I can easily make a matrix of plots with m
rows and n
columns.
In special cases, there is a pattern in the plots, such that all the plots in each column share an important attribute, and all the plots in each row share a different important attribute. All such information can be included in the title of each of the m*n
plots individually, but this is obviously repetitive.
Is there a convenient way to append column names (only above the top row of plots) and row names (only to the left of the left column of plots) in such a grid?
Best solution so far: Use the text()
command to place text outside of the left-and-top plots. But this is pretty unsatisfactory, as it requires many separate commands, and tweaking arguments such as srt = 90
to make the text vertical on the left margin, and using xpd = NA
inside of par()
.
The lattice and ggplot2 packages have tools for creating multiple plots in a grid. They may speed up your entire process if they apply to what you want to do.
library(lattice)
splom( ~ iris[,1:4], data=iris, groups=Species )
xyplot( mpg ~ wt | factor(cyl)*factor(am), data=mtcars )
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + facet_grid(am ~ cyl)
Using base graphics you can start by setting an outer margin, see the oma
argument to the par
command, then use the mtext
function to write the text into the outer margin for your labels.
par( oma=c(0,6,6,0), mfrow=c(2,2), mar=c(2,2,1,1)+0.1 )
with(iris, plot(Sepal.Width, Petal.Width, ann=FALSE))
mtext( 'Width', side=3, line=2, at=grconvertX(0.5,'npc','nic'), outer=TRUE )
mtext( 'Width', side=2, line=2, at=grconvertY(0.5,'npc','nic'), outer=TRUE )
mtext( 'Sepal', side=3, line=4, outer=TRUE, cex=2 )
mtext( 'Petal', side=2, line=4, outer=TRUE, cex=2 )
with(iris, plot(Sepal.Length, Petal.Width, ann=FALSE))
mtext( 'Length', side=3, line=2, at=grconvertX(0.5,'npc','nic'), outer=TRUE )
with(iris, plot(Sepal.Width, Petal.Length, ann=FALSE))
mtext( 'Length', side=2, line=2, at=grconvertY(0.5, 'npc','nic'), outer=TRUE )
with(iris, plot(Sepal.Length, Petal.Length, ann=FALSE))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With