0

I’m having trouble exporting plots in ggplot. I want to display my data using different variables in different plots and have the plot panel size export to the same size every time. My issue is that sometimes my legends are wider or shorter and R ends up smushing my plot to accommodate for the size of the legend. I want the plot panel to print in the same dimensions every time, and for R to stretch the width of the image it exports to accommodate the varying sizes of legends.

p1 p2

library(ggplot2)
my_data <- data.frame(
  Name = c("Alice Smith", "Eduardo Fernandez", "Steven Brown"),
  Age = c(25, 30, 22),
  Gender = c("Female", "Male", "Male"),
  Height = c(165, 180, 175))

p1 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender))+
  geom_point(size = 2, stroke = 1)
p1

ggsave(filename = "p1.png",
       plot = p1,
       device = "png",
       height = 7,
       width = 10,
       units = "in",
       dpi = 500,
       bg="black")
dev.off()

p2 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender,shape=Name))+
  geom_point(size = 2, stroke = 1)
p2

ggsave(filename = "p2.png",
       plot = p2,
       device = "png",
       height = 7,
       width = 10,
       units = "in",
       dpi = 500,
       bg="black")
dev.off()

I know that technically you can do this by making your export width wider or smaller and checking every single time to make sure that the panel is the same size but it’s so time consuming. I have been painstakingly exporting the plots .2 inches wider at a time and checking to see if the panels are exactly the same until I get it right. There must be a better way.

axc
  • 3
  • 2
  • relevant question: https://stackoverflow.com/questions/53285493/explicitly-set-panel-size-not-just-plot-size-in-ggplot2 – AndS. Jul 29 '23 at 01:52

1 Answers1

2

As described further in the help, patchwork has the get_dim and get_max_dim functions so you can apply the plot dimensions of another plot.

library(patchwork)
set_dim(p1, get_max_dim(p1, p2))

enter image description here

and set_dim(p2, get_max_dim(p1, p2))

enter image description here


test using ggsave:

set_dim(p1, get_max_dim(p1, p2))
ggsave("p1.png", height = 3)

set_dim(p2, get_max_dim(p1, p2))
ggsave("p2.png", height = 3)

enter image description here

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Thank you! This worked in my R plot viewer but when I exported them using ggsave the dimensions were still off. Is the problem with ggsave? is there something else I can use that's better? – axc Aug 03 '23 at 18:41
  • Can you share a reproducible example of it not working using ggsave? I've edited my answer to show an example that worked as expected. – Jon Spring Aug 03 '23 at 18:50