How to align grob with ggplot using ggplotGrob and annotation_custom?

Viewed 90

I am creating a grob from a ggplot using ggplotGrob and then adding it as a background layer in a complex ggplot construction using annotation_custom since the performance is much improved in a facet_wrap plot with a large dataset. However I am unable to align the underlying grob correctly with the ggplot.

This simple example shows the issue I am trying to solve.

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(color = "red")
ggplot(mtcars, aes(wt, mpg)) +
  annotation_custom(grob = ggplotGrob(p)) +
  geom_point()

ggplotGrob background layer

I want the plot with red points to be perfectly underneath the plot with black points.

1 Answers

You'd probably want to grab just the panel without axis, margins etc. before adding it as a custom annotation then. In example below, I made the red points larger so you can see that they overlap.

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(color = "red", size = 3)

grab_panel <- function(p) {
  gt <- ggplotGrob(p)
  layout <- gt$layout
  is_panel <- which(layout$name == "panel")[[1]]
  i <- layout$t[is_panel]
  j <- layout$l[is_panel]
  gt[i,j]
}

ggplot(mtcars, aes(wt, mpg)) +
  annotation_custom(grob = grab_panel(p)) +
  geom_point()

Created on 2021-03-20 by the reprex package (v1.0.0)

Related