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:
- row1 - title of plot ("Sample Plot" at the center)
- row2 - p1[[1]], p1[[2]], p1[[3]] (each with legend at bottom)
- row3 - p1[[4]], p1[[5]], p2 (no legends,
but
get_legend()
from p2) - 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)
See if this works for you: