Home > Back-end >  Sizing a ggplot precisely
Sizing a ggplot precisely

Time:11-05

I have got two ggplots, of which I want the size of the grey area to be exactly equal.

Now by playing around I can get very close by setting first plot width to 12 and second plot width to 14.

ggsave(filename="test1.png", myPlot, width = 12, height =12, dpi=300, units="cm", device='png')
ggsave(filename="test2.png", myPlot, width = 14, height =12, dpi=300, units="cm", device='png')

enter image description here

My question is whether I can pull some variable(s) from the first plot, so that I can automatically compute the right width for the second plot (ie, the width that makes the grey areas identical in size).

CodePudding user response:

Aside from the options already given by Allan, you might also find ggh4x::force_panelsizes() convenient to set sizes for plots (disclaimer: I wrote it).

library(ggplot2)

a <- ggplot(mpg, aes(displ, hwy, colour = cyl))  
  geom_point()

b <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species))  
  geom_point()  
  guides(y.sec = "axis")

a   ggh4x::force_panelsizes(rows = unit(4, "cm"), cols = unit(5, "cm"))

b   ggh4x::force_panelsizes(rows = unit(4, "cm"), cols = unit(5, "cm"))

Created on 2022-11-04 by the enter image description here

Created on 2022-11-04 with reprex v2.0.2

  • Related