I created two plots with different aspect ratios, adjusted them with theme(aspect.ratio = ...)
and joined them into a single picture using the patchwork
package.
When I save the picture as a PDF, I need the width to be 10 cm, but the height of the picture isn't defined because it depends on the aspect ratio I've indicated for each plot and the caption.
I used ggsave
to save the picture as a PDF, specified a width of 10 cm and didn't set the height, thinking that it would be adjusted automatically. The height was adjusted automatically but left a lot of blank space.
When I don't specify the aspect ratio of each plot, the PDF picture takes up all the available area. How can I get the same result by specifying the aspect ratio of each plot?
library(ggplot2)
library(patchwork)
p1 <- ggplot(data = mtcars,
aes(x = cyl,
y = hp,
color = as.factor(vs))) +
geom_line() +
theme(aspect.ratio = 0.5)
p2 <- ggplot(data = mtcars,
aes(x = mpg,
y = carb,
color = as.factor(vs))) +
geom_line() +
theme(aspect.ratio = 0.25)
p <- p1 / p2 +
plot_annotation(tag_levels = "a",
tag_prefix = "(",
tag_suffix = ")") +
plot_layout(guides = 'collect') &
theme(legend.position='bottom')
ggsave("example.pdf",
plot = p,
width = 10,
#height = ??,
units = "cm",
device = cairo_pdf)
Example with a specified aspect ratio
Example without a specified aspect ratio