Home > Blockchain >  How How to add annotations to plots AND keep the boxes on the top (by ggplot2)?
How How to add annotations to plots AND keep the boxes on the top (by ggplot2)?

Time:01-18

I want to add annotations to each plot, but when I use tag_facet() the grey box on top of plots disappears. How to add annotations to plots AND keep the boxes on the top?

Thanks for any help.

enter image description here

enter image description here

CodePudding user response:

The source code for egg::tag_facet() from here is:

tag_facet <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf, 
                      hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {
  
  gb <- ggplot_build(p)
  lay <- gb$layout$layout
  tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
  p   geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust, 
                vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE)   
                theme(strip.text = element_blank(), strip.background = element_blank())
}

you could alternatively define a function that doesn't change the theme as:

tag_facet2 <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf, 
                      hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {
  
  gb <- ggplot_build(p)
  lay <- gb$layout$layout
  tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
  p   geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust, 
                vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE)
}
  • Related