thomasp85 / patchwork

The Composer of ggplots
https://patchwork.data-imaginist.com
Other
2.42k stars 157 forks source link

wrap_ggplot_grob() doesn't work with plot_annotation() tags #363

Open dchiu911 opened 2 months ago

dchiu911 commented 2 months ago

How do we annotate a ggplot object result from wrap_ggplot_grob() with tags ?

library(patchwork)
library(grid)
library(gtable)
library(ggplot2)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + ggtitle('disp and mpg seems connected')
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

# Convert p2 so we can add new stuff to it
p2_table <- ggplotGrob(p2)
stamp <- textGrob('TOP SECRET', rot = 35,
                  gp = gpar(fontsize = 72, fontface = 'bold')
)
p2_table <- gtable_add_grob(p2_table, stamp,
                            t = 1, l = 1, b = nrow(p2_table), r = ncol(p2_table)
)

# Adding it directly will loose alignment
p1 + p2_table


# Use wrap_ggplot_grob to keep alignment
p1 + wrap_ggplot_grob(p2_table) + plot_annotation(tag_levels = "A")

Created on 2024-05-14 with reprex v2.1.0