сложность использования plot_grid и get_legend в R

Мне трудно использовать plot_grid() и get_legend() в коровьем заговоре в R

Я создал шесть графиков, используя приведенный ниже пример кода. Я хочу использовать plot_grid() в коровьем графике, чтобы расположить его в 4 ряда:

  1. row1 - название участка (Образец участка в центре)
  2. row2 - p1 [[1]], p1 [[2]], p1 [[3]] (каждый с легендой внизу)
  3. row3 - p1 [[4]], p1 [[5]], p2 (без легенд, но get_legend() из p2)
  4. row4 - легенда графика, извлеченная из p2 (выровненная по горизонтали), она должна отображаться как общая легенда среди графиков в строке 3

относительная высота строк ‹- c(1, 4, 4, 1)

Кто-нибудь может поделиться кодом желаемого сюжета?

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)

person SiD    schedule 05.12.2020    source источник


Ответы (1)


Посмотрите, работает ли это для вас:

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

результат

person Z.Lin    schedule 16.12.2020