Creating different graphs in R with the same aspect ratio

I created a function to create forest plots that have labels on the y axis. I need to create several of them to join an external graphics program.

Graph images will have the same width, but the height will change according to the number of elements y. To do this, I first created a graph and manually set the height of the image ( i.h1). Then I subtracted the i.h1top ( u.m) and bottom ( b.m) edge to get the height of the graph. Finally, I divided the height of the graph by the number of labels y n1to get the unit u = (i.h1 - b.m - u.m) / n1.

To get the size of the next image, h.i2I just needed to h.i2 = u * n2 + b.m + u.m.

Here is the result in the first image with 27 elements (counting spaces) and the second image with 6 elements.

The second image is much higher than it should be! (purple lines for comparison).

In addition, the internal field between the bottom element and the x axis is different. Therefore, even if I use different device heights, I get shortcuts in two images that are not aligned.

enter image description here

I do not understand this behavior. Any hint?

Here is the code to save the image:

gt <- ggplot_gtable(ggplot_build(plot)) #plot is a ggplot object
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

if (file != F) {
    w = 8.5
    h = .33 * max(data$yval) + 4 # .33 is the unit height and 4 are the margin

    dev.copy(pdf, if (file == T) sprintf("%s.pdf", gsub('\\n', '', title)) else file, width = w, height = h) # I use dev.copy because ggsave don't accept gtable plots.

    invisible(dev.off())
}
+4
source share

Source: https://habr.com/ru/post/1618946/


All Articles