将图例插入不同的图形

insert a legend to a distinct graph

我有一个系统发育树,如下图。

我确实制作了一个假数据框来获取图例,现在我想将该图例插入到系统发育树的中心。我用了 grid.arrange 但我无法移动图例位置。

我创造的假传说

df <- data.frame(name = c("ANA-GRADE", "ASTERIDS","BASAL EUDICOTS", "BASAL SUPERASTERIDS",
                          "CHOLORANTHALES", "MAGNOLIIDS", "MONOCOTS","ROSIDS",
                          "ANA-GRADE", "ASTERIDS","BASAL EUDICOTS", "BASAL SUPERASTERIDS",
                          "CHOLORANTHALES", "MAGNOLIIDS", "MONOCOTS","ROSIDS"),
                 colour = c("#EFF13A", "#428d34", "#84cf70", "#62a852", "#CDD100", 
                            "#8B5742", "#EEAD0E", "#2d7a21", "#EFF13A", "#428d34", 
                            "#84cf70", "#62a852", "#CDD100", "#8B5742", "#EEAD0E", "#2d7a21"),
                 x1 = runif(16, 5,100),
                 y1 = runif(16, 20,50))

fake <- df %>% ggplot(aes(x1,y1, colour = name)) +
  geom_line(size = 1) +
  scale_colour_manual(values = c("#EFF13A", "#428d34", "#84cf70", "#62a852", "#CDD100", 
                       "#8B5742", "#EEAD0E", "#2d7a21"),
                      name = "Major clade") +
  theme_bw() +
  theme(legend.title = element_text(face = "bold",size = 12))

legend <- get_legend(fake)

# using grid.arrange

有人对我使用 grid.arrange 有什么建议吗?

cowplot 中的新 ggdraw 函数提供了一种选择。

它接受任何 grob,而不仅仅是 ggplot 对象。

library(tidyverse)
library(cowplot)

df <- data.frame(name = c("ANA-GRADE", "ASTERIDS","BASAL EUDICOTS", "BASAL SUPERASTERIDS",
                          "CHOLORANTHALES", "MAGNOLIIDS", "MONOCOTS","ROSIDS",
                          "ANA-GRADE", "ASTERIDS","BASAL EUDICOTS", "BASAL SUPERASTERIDS",
                          "CHOLORANTHALES", "MAGNOLIIDS", "MONOCOTS","ROSIDS"),
                 colour = c("#EFF13A", "#428d34", "#84cf70", "#62a852", "#CDD100", 
                            "#8B5742", "#EEAD0E", "#2d7a21", "#EFF13A", "#428d34", 
                            "#84cf70", "#62a852", "#CDD100", "#8B5742", "#EEAD0E", "#2d7a21"),
                 x1 = runif(16, 5,100),
                 y1 = runif(16, 20,50))

fake <- 
  df %>% ggplot(aes(x1,y1, colour = name)) +
  geom_line(size = 1) +
  scale_colour_manual(values = c("#EFF13A", "#428d34", "#84cf70", "#62a852", "#CDD100", 
                                 "#8B5742", "#EEAD0E", "#2d7a21"),
                      name = "Major clade") +
  theme_bw() +
  theme(legend.title = element_text(face = "bold",size = 12))


sample_donut_plot <- 
  data.frame() %>%
  ggplot(aes(ymin = 0, ymax = 1, xmin = 3, xmax = 4), ) + 
  geom_rect() + 
  coord_polar(theta="y") +
  xlim(c(0, 4)) +
  theme_void()

legend <- cowplot::get_legend(fake)

cowplot::ggdraw(sample_donut_plot) +
  cowplot::draw_plot(legend, x = .25, y = .25, width = .5, height = .5) 

reprex package (v2.0.1)

于 2021-10-25 创建