如何使用R中的grid.arrange并排排列的图形/边框

时间:2014-09-02 06:00:46

标签: r ggplot2 border gridextra

我使用ggplot创建了两个图,如下所示:

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)

我想在grid.arrange生成的两个并排图周围绘制一个边框/框...我认为这与使用grid.border有关,但我不确定如何做到这一点。会不会感激任何帮助?

1 个答案:

答案 0 :(得分:2)

使用ggplot帮助页面中的示例:

 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)

或许这取决于你的意见:

 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)

如果您只想要一个边框:

grid.rect(.5,.5,width=unit(.99,"npc"), height=unit(0.99,"npc"), 
          gp=gpar(lwd=3, fill=NA, col="blue"))