在网格的一部分上锁定纵横比

3
我正在尝试编写一个函数,其中我们公司的标志将自动添加到每个图表中,并作为功能的一部分导出到标题和副标题旁边。每个输出的尺寸将取决于当时的需求,因此设定固定的尺寸不会特别有帮助。
为了实现这一点,我已经生成了一系列网格来组合所有元素,如下所示(使用鸢尾花数据集)。
library(datasets)
library(tidyverse)
library(gridExtra)
library(grid)
library(png)

m <- readPNG("Rlogo.png") # download from: https://www.r-project.org/logo/Rlogo.png

plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_col() +
  ggtitle("Title goes here",
          subtitle = "subtitle down here")


txtTitle <- plot$labels$title
txtSubTitle <- plot$labels$subtitle

plot$labels$title <- NULL
plot$labels$subtitle <- NULL

buffer <- grobTree(rectGrob(gp = gpar(fill = "white", col = "white")))

Title <- grobTree(textGrob(label = txtTitle,  
                           hjust = 1, 
                           x = 0.98))
SubTitle <- textGrob(label = txtSubTitle, 
                     hjust = 1, 
                     x = 0.98)
Logo <- grobTree(rasterGrob(m, x = 0.02, hjust = 0))



TitlesGrid <- grid.arrange(Title, SubTitle, ncol = 1)
TopGrid <- grid.arrange(Logo, TitlesGrid, widths = c(1, 7), ncol = 2)
AllGrid <- grid.arrange(TopGrid, arrangeGrob(plot), heights = c(1,7))

以下是不同宽高比下的输出结果。 Good spacing Bad Output 第一个示例的标题和副标题之间有足够的空隙,而第二个示例中则过多。如何使TopGrid的高度固定为绝对大小,但其余部分可按需填充?

我认为这将需要选择支持此类属性规范的输出格式,例如PDF?我怀疑使用PNG、JPEG或TIFF可能无法实现。也许您可以创建某种伪设备,将固定大小的图形与“其他内容”合并? - IRTFM
1个回答

4

网格图形具有绝对和相对单位的概念。绝对单位(如“cm”、“in”、“pt”)始终保持相同的大小,不受视口大小的影响。相对单位(称为“null”)根据需要扩展或缩小。在常规的ggplot2对象中,绘图面板以相对单位指定,而面板周围的各种元素(如标题、轴刻度等)以绝对单位指定。

您可以使用unit()函数指定绝对或相对单位:

> library(grid)
> unit(1, "cm")
[1] 1cm
> unit(1, "null")
[1] 1null

在您的情况下,grid.arrangeheights 参数可以采用任意网格单位对象,因此您只需要给顶部高度一个绝对单位:

grid.arrange(TopGrid, arrangeGrob(plot), heights = unit(c(1, 1), c("cm", "null")))

enter image description here

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接