Adding a border to a grid of plots in R
border, ggplot2, r, r-grid
Solution
You can use `grid.rect` for example. I would put it in a separate `viewport` before plotting your plot. I mean:
- I push the first viewport , I plot the rectangle(the frame)
- I push the seconde Viewport, I create all your plots.
- I pop my 2 viewports
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)
Problem
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.