user2183835
user2183835

Reputation: 51

Adding a border to a grid of plots in R

I have created a series of plots using ggplot and printed them in a grid. I would like to add a border around the entire grid so that when I insert the image into a presentation, it is clearly defined.

This is the creation of the grid and the printing commands that I am using. I have imported all the necessary packages.

library(grid)
pushViewport(viewport(gp=gpar(col="white"), 
             layout = grid.layout(4, 2, heights = unit(c(0.5,5,5,5), "null"))))  
grid.text("Summer Clear Day- August 2, 2012", 
          vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2))
grid.frame(gp=gpar(col="white"), draw=TRUE)
print(tot, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(gh, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
print(dir, vp = viewport(layout.pos.row = 3, layout.pos.col = 1))
print(ir, vp = viewport(layout.pos.row = 3, layout.pos.col = 2))
print(dh, vp = viewport(layout.pos.row = 4, layout.pos.col = 1))
print(uv, vp = viewport(layout.pos.row = 4, layout.pos.col = 2))

grid.frame doesn't seem to do anything. My background is black so I hope to create a white border around it.

Upvotes: 4

Views: 2770

Answers (2)

baptiste
baptiste

Reputation: 77116

A compact version of @agstudy's answer:

  require(gridExtra)
  grid.draw(grobTree(arrangeGrob(k1, k1, k1, k1, k1, k1, ncol=2,
                       main="Summer Clear Day- August 2, 2012"), 
                     rectGrob(gp=gpar(lwd=2, fill=NA))))

Upvotes: 5

agstudy
agstudy

Reputation: 121608

You can use grid.rect for example. I would put it in a separate viewport before plotting your plot. I mean:

  1. I push the first viewport , I plot the rectangle(the frame)
  2. I push the seconde Viewport, I create all your plots.
  3. I pop my 2 viewports

enter image description here

pushViewport(plotViewport(c(5,5,5,5)))
grid.rect()
grid.rect(width=unit(1, "npc")-unit(0.5,'lines'),
          height=unit(1, "npc")-unit(0.5,'lines'))
pushViewport(plotViewport(c(1,1,1,1),
                      layout = grid.layout(4, 2, 
                                           heights =     unit(c(1,5,5,5), "null")))) 
grid.text("Summer Clear Day- August 2, 2012", 
          vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2))
k1 <- ggplot(mtcars, aes(factor(cyl), mpg))  + geom_boxplot()

print(k1, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(k1, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
print(k1, vp = viewport(layout.pos.row = 3, layout.pos.col = 1))
print(k1, vp = viewport(layout.pos.row = 3, layout.pos.col = 2))
print(k1, vp = viewport(layout.pos.row = 4, layout.pos.col = 1))
print(k1, vp = viewport(layout.pos.row = 4, layout.pos.col = 2))
upViewport(2)

Upvotes: 5

Related Questions