3

I have created two plots using ggplot as follows:

library(ggplot2)
library(gridExtra)
g1 <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
g2 <- ggplot(iris, aes(Petal.Width, Petal.Length)) + geom_point()
grid.arrange(g1, g2, ncol=2)

I would like to draw a border/box around the two side by side plots produced by grid.arrange...I think it is something to do with using grid.border, but am not sure of how exactly to do so. Will appreciate any help?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • Welcome to SO! You might have been downvoted because it is usually a good idea to post a question with a complete [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) example and the full code that can be run via copy-paste. – tonytonov Sep 02 '14 at 07:41
  • Apologize...first time posting.Thanks for editing – Ramesh Maganti Sep 02 '14 at 10:18

1 Answers1

2

Using an example from the ggplot help page:

 gg <- df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
                  y = rnorm(30))

 library(plyr)
 ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
 gg2 <-ggplot(df, aes(x = gp, y = y)) +
    geom_point() +
    geom_point(data = ds, aes(y = mean),
               colour = 'red', size = 3)+theme(panel.border=element_rect(fill=NA) )
 grid.arrange(gg2,gg2, ncol=2)

Or perhaps this depending on your meeaning:

 gg2 <-ggplot(df, aes(x = gp, y = y)) +
    geom_point() +
    geom_point(data = ds, aes(y = mean),
               colour = 'red', size = 3)+theme(plot.background = element_rect(size=3,linetype="solid",color="black"))
 grid.arrange(gg2,gg2, ncol=2)

If you just want a bordering rectangle:

grid.rect(.5,.5,width=unit(.99,"npc"), height=unit(0.99,"npc"), 
          gp=gpar(lwd=3, fill=NA, col="blue"))
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 2
    the solution above does not draw the border/box around both the unrelated plots? i am looking for one box/border that encloses all the plots produced by grid.arrange. thanks – Ramesh Maganti Sep 02 '14 at 10:28
  • you might want to set `fill=NA` explicitly, as it may default to "white" on some devices, thereby covering the plots below. – baptiste Sep 02 '14 at 17:06
  • Good point. That did occur to me on a machine that was running earlier version of R although not on 3.1.0 just now. – IRTFM Sep 02 '14 at 17:14