[R] Axis Labels for Compound Plots in ggplot2

baptiste auguie baptiste.auguie at googlemail.com
Wed Dec 30 13:27:34 CET 2009


Hi,

You can set up a Grid layout with one viewport at the bottom and
another on the left and use grid.text to add your labels. An example
is given below using grid.pack.

The gridExtra package provides a convenient wrapper for these regular
arrangements of plots,

##library(gridExtra) #http://gridextra.googlecode.com/
source("http://gridextra.googlecode.com/svn/trunk/R/arrange.r")

arrange(a, b, c, d)

I will add a viewport on the left side for a global y axis, but in the
meantime you can use packGrob,

## return a grob with all plots
p <- arrange(a, b, c, d, plot=FALSE)

g <- frameGrob()
g <- packGrob(g, p)
g <- packGrob(g, textGrob("my y label", rot=90), side = "left",
              border = unit(rep(4, 4), "mm"))
g <- packGrob(g, textGrob("my x label"), side = "bottom",
              border = unit(rep(4, 4), "mm"))

grid.draw(g)


HTH,

baptiste


2009/12/30 Lorenzo Isella <lorenzo.isella at gmail.com>:
> Dear All,
> I am trying to stitch together multiple plots using ggplot2
> Consider for instance the following snippet based on an old thread
> (http://tinyurl.com/ylehm2t)
>
> library(ggplot2)
> vplayout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
>
> draw4 <- function(pdfname, a,b,c,d,w,h) {
>
>   pdf(pdfname,width=w, height=h)
>   grid.newpage()
>   pushViewport(viewport(layout=grid.layout(2,2) ) )
>
>       print(a, vp=vplayout(1,1))
>       print(b, vp=vplayout(1,2))
>       print(c, vp=vplayout(2,1))
>       print(d, vp=vplayout(2,2))
>
>
>   dev.off()
> }
>
> data(diamonds)
>
>
> set.seed(1234)
>
> randind <- sample(nrow(diamonds),1000,replace=FALSE)
> dsmall <- diamonds[randind,]
>
> a <-  qplot(carat, data=dsmall, geom="histogram",binwidth=1)
> b <-  qplot(carat, data=dsmall, geom="histogram",binwidth=.1)
> c <- qplot(carat, data=dsmall, geom="histogram",binwidth=.01)
> d <- qplot(carat, data=dsmall, geom="histogram",binwidth=2)
>
> width <- 7
> height <- 7
>
> draw4( "test-4.pdf", a,b,c,d, width, height)
>
>
> Is there any way to give an overall label along the y and x axis?
> E.g.something like a xlab to write some text which applies to the x axis
> of all the plots and which should go at the middle bottom of the
> compound plot (and something perfectly along these lines for the y axis).
> Many thanks
>
> Lorenzo
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list