Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a "grid" between arranged plots

Tags:

r

ggplot2

ggpubr

I'm working with 4 different plots and I'm using ggarrange() from the ggpubr-package to put them in a single plot. I've prepared an example:

library(ggpubr)
library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 1")
p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 2")
p3 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 3")
p4 <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 4") +
  facet_wrap(~Species)

plot.list <- list(p1, p2, p3, p4)

ggarrange(plotlist = plot.list)

Output: enter image description here

I would like to draw a border around the single plots, like so:

enter image description here

Is there any way to draw this border? Thanks!

like image 874
brettljausn Avatar asked Jul 05 '19 10:07

brettljausn


Video Answer


1 Answers

grid.polygon() is quite manual but I think it can do the trick:

Using RStudio

library("ggpubr")
library(ggplot2)
library(gridExtra)
library(grid)
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 1")
p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 2")
p3 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 3")
p4 <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 4") +
  facet_wrap(~Species)

plot.list <- list(p1, p2, p3, p4)

ggarrange(plotlist = plot.list)
x = c(0, 0.5, 1, 0.5, 0.5, 0.5)
y = c(0.5, 0.5, 0.5,0, 0.5, 1)
id = c(1,1,1,2,2,2)
grid.polygon(x,y,id)

enter image description here Using Shiny (Edit)

When doing it within a shiny-app, ones needs to add the grid using annotation_custom(), as follows:

    ggarrange(plotlist = plot.list) + 
    annotation_custom(
             grid.polygon(c(0, 0.5, 1, 0.5, 0.5, 0.5),
                          c(0.5, 0.5, 0.5,0, 0.5, 1), 
                          id = c(1,1,1,2,2,2), 
                          gp = gpar(lwd = 1.5)))
like image 180
Carles S Avatar answered Nov 09 '22 01:11

Carles S