Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 827
user2183835 Avatar asked Dec 27 '22 07:12

user2183835


2 Answers

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)
like image 71
agstudy Avatar answered Jan 05 '23 02:01

agstudy


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))))
like image 22
baptiste Avatar answered Jan 05 '23 03:01

baptiste