How to draw a box/border around plots arranged side by side using grid.arrange in R

£可爱£侵袭症+ 提交于 2019-12-07 17:43:41

问题


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?


回答1:


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"))


来源:https://stackoverflow.com/questions/25616788/how-to-draw-a-box-border-around-plots-arranged-side-by-side-using-grid-arrange-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!