Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a matrix of plots with row and column titles

Tags:

plot

r

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().

like image 563
zkurtz Avatar asked Jun 26 '14 18:06

zkurtz


1 Answers

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))
like image 163
Greg Snow Avatar answered Sep 19 '22 00:09

Greg Snow