Гроб 3 легенды на наложенном сюжете - PullRequest
0 голосов
/ 03 октября 2019

Я пытаюсь нарисовать три легенды в этом наложенном ggplot2. У меня есть три графика, и я беру цвета для каждого, чтобы можно было наложить цвета плотности для трех групп, но мне не удается создать гробовые легенды. Таким образом, в заключительном сюжете я не могу добавить все три легенды.

commonTheme = list(labs(color="Density",fill="Density",
                        x="Anueploidy",
                        y="Divergence"),
                   theme_bw(),
                   theme(legend.position=c(0,1),
                         legend.justification=c(0,1)))


# plot 1
p1 <- ggplot(data = all_scores, aes(anueploidy, score, colour=type)) + theme_cowplot(12) +
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
  scale_fill_continuous(low ="white", high = "#ea7e5d", space = "Lab", name = "adenomas") +
  scale_colour_discrete(guide = FALSE) +
    geom_point() + commonTheme

# plot 2
p2 <- ggplot(data = all_scores, aes(anueploidy, score, colour=type)) +
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
  scale_fill_continuous(low = "white", high = "#5deac5", space = "Lab", name = "ca-in-ads") +
  scale_colour_discrete(guide = FALSE) +
    geom_point() + commonTheme


# plot 3
p3 <- ggplot(data = all_scores, aes(anueploidy, score, colour=type)) +
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
  scale_fill_continuous(low = "white", high = "#5d83ea", space = "Lab", name = "crcs") +
  scale_colour_discrete(guide = FALSE) +
    geom_point() + commonTheme


# grab plot data
pp1 <- ggplot_build(p1)
pp2 <- ggplot_build(p2)$data[[1]]
pp3 <- ggplot_build(p3)$data[[1]]

# replace red fill colours in pp1 with blue colours from pp2 when group is 2
pp1$data[[1]]$fill[grep(pattern = "^2", pp2$group)] <- pp2$fill[grep(pattern = "^2", pp2$group)]

pp1$data[[1]]$fill[grep(pattern = "^3", pp3$group)] <- pp3$fill[grep(pattern = "^3", pp3$group)]


# build plot grobs
grob1 <- ggplot_gtable(pp1)
grob2 <- ggplotGrob(p2)
grob3 <- ggplotGrob(p3)

# build legend grobs
leg1 <- gtable_filter(grob1, "guide-box") 
leg2 <- gtable_filter(grob2, "guide-box") 
leg3 <- gtable_filter(grob3, "guide-box")
leg <- gtable:::rbind_gtable(leg1[["grobs"]][[1]],  c(leg2[["grobs"]][[1]], leg3[["grobs"]][[1]]), "first")


# replace legend in 'red' plot
grob1$grobs[grob1$layout$name == "guide-box"][[1]] <- leg


# plot
grid.newpage()
grid.draw(grob1)

но не все легенды всплывают. Есть ли способ, которым я могу их объединить?

...