简体   繁体   中英

Adding a grob to patchwork plot R

I have a function that returns a patchwork plot and I can't make any changes to. I would like to add a rectGrob() on top of it. When I try to do this I remove two of the plots.

library(gridExtra)
library(patchwork)
library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
p2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point()
p3 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width), col = 'blue') + geom_point()

p <- p1 + p2 + p3

grob_top <-   grobTree(rectGrob(gp=gpar(fill='#F0F0F0',col= 'black')), textGrob('P1,P2, P3'))

grid.arrange(grob_top, p, heights = c(0.1, 0.9))

Using patchwork::wrap_elements() works better than gridExtra::grid.arrange()

patchwork::wrap_elements(grob_top) / 
patchwork::wrap_elements(p) / 
patchwork::wrap_elements(p) + 
patchwork::plot_layout(ncol = 1, heights = c(0.1, 0.45, 0.45))

I think you want:

grid.arrange(grob_top,
             p,
             nrow = 2,
             heights = c(0.1, 0.9))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM