difficulty in using plot_grid and get_legend in R

869 Views Asked by At

I am finding difficulty in using plot_grid() and get_legend() in cowplot in R

I generated six plots using the sample code below. I want to use plot_grid() in cowplot to arrange in 4 rows:

  1. row1 - title of plot ("Sample Plot" at the center)
  2. row2 - p1[[1]], p1[[2]], p1[[3]] (each with legend at bottom)
  3. row3 - p1[[4]], p1[[5]], p2 (no legends, but get_legend() from p2)
  4. row4 - plot legend extracted from p2 (horizontally aligned), it should appear as shared legend among plots in row 3

relative heights of rows <- c(1, 4, 4, 1)

Can someone please share the code for the desired plot?

library(tidyverse)
library(cowplot)

# FIRST FIVE PLOT
p1 <- list()
for (iter in 1:5)
{
  # generate random points
  x <- rnorm(100, mean = 0, sd = 1)
  y <- rnorm(100, mean = 0, sd = 1)
  # random array of 0 and 1
  choice <- sample(c(0,1), replace=TRUE, size=100)
  
  # tibble
  tbl <- tibble(x, y, choice)
  
  # plot
  p1[[iter]] <- ggplot(data = tbl,
                      aes(x = x, 
                          y = y,
                          color = choice)) +
    geom_point() +
    theme(legend.position = "bottom")
}


# SIXTH PLOT
# generate random points
x <- rnorm(100, mean = 5, sd = 5)
y <- rnorm(100, mean = 5, sd = 5)
# random array of 0 and 1
choice <- sample(c(0,1), replace=TRUE, size=100)

# tibble
tbl <- tibble(x, y, choice)

# plot
p2 <- ggplot(data = tbl,
                    aes(x = x, 
                        y = y,
                        color = choice)) +
  geom_point() +
  theme(legend.position = "right")

title <- "Sample Plot"
# to be edited
plot_grid(p1[[1]], p1[[2]], p1[[3]],
          p1[[4]], p1[[5]], p2,
          nrow = 2)
1

There are 1 best solutions below

0
On

See if this works for you:

# get title as a grob object
grob_title <- get_plot_component(p2 + ggtitle(title) +
                                   theme(plot.title = element_text(hjust = 0.5)), 
                                 "title", 
                                 return_all = TRUE)[[2]]

plot_grid(
  # row 1: center-aligned title
  grob_title,
  
  # row 2: 3 plots from list, each with legends intact
  plot_grid(plotlist = p1[seq(1, 3)], 
            nrow = 1),
  
  # row 3: 2 plots from list + p2, all with legend removed
  plot_grid(p1[[4]] + theme(legend.position = "none"), 
            p1[[5]] + theme(legend.position = "none"), 
            p2 + theme(legend.position = "none"),
            nrow = 1),
  
  # row 4: legend from p2, lengthened (width can be adjusted) & rotated 
  get_legend(p2 + 
               theme(legend.key.width = unit(2, "cm"),
                     legend.position = "bottom")),
  
  ncol = 1, rel_heights = c(1, 4, 4, 1))

result