rggplot2ggh4x

set position / alignment of ggplot in separate pdf-images after setting absolute panel size


I am creating various ggplots with identical x-axes and varying y-axes. I would like the panels to be the same size and be in the same position in their separate pdf-images (for the slides of a LaTeX beamer presentation).

Whether I fix the size of the panels using the ggh4x package or the egg package, the plot is centered in the image, and consequently, the position of the panel changes across PDFs.

Is there a way to either specify the position of the panel within the plot or fix the right margin?

library(ggplot2)
library(ggh4x)
library(egg)

p1 <- ggplot(mpg, aes(x = hwy, y = cty)) +
  geom_point()
p2 <- ggplot(mpg, aes(x = hwy, y = cty*10000)) +
  geom_point()

p1.egg <- set_panel_size(p1, width  = unit(3, "cm"),
                           height = unit(3, "cm"))
p2.egg <- set_panel_size(p2, width  = unit(3, "cm"),
                           height = unit(3, "cm"))
ggsave(plot = p1.egg, filename = "p1egg.pdf", height = 5, width = 6, units = "cm")
ggsave(plot = p2.egg, filename = "p2egg.pdf", height = 5, width = 6, units = "cm")

p1.ggh4x <- p1 + force_panelsizes(cols = unit(3, "cm"),
                                  rows = unit(3, "cm"))
p2.ggh4x <- p2 + force_panelsizes(cols = unit(3, "cm"),
                                       rows = unit(3, "cm"))
ggsave(plot = p1.ggh4x, filename = "p1ggh4x.pdf", height = 5, width = 6, units = "cm")
ggsave(plot = p2.ggh4x, filename = "p2ggh4x.pdf", height = 5, width = 6, units = "cm")


Solution

  • It looks to me like the issue is that your axes take different amounts of space, and each panel is sized in relation to its own axes. patchwork has a variety of functions to align plots. There might be equivalents in egg or ggh4x that I don't know about.

    https://patchwork.data-imaginist.com/articles/guides/multipage.html

    library(patchwork)
    p1b <- p1 |> set_dim(get_max_dim(p1, p2))
    p2b <- p2 |> set_dim(get_max_dim(p1, p2))
    

    This looks for the largest border dimensions needed in either of the plots, and applies those to each, so the plots are aligned, regardless of their axis text.

    When I output these to pdf, they look aligned. If they don’t for you, please share more detail about how the output differs from your goal.

    enter image description here

    and this separate plot:

    enter image description here