我正在尝试写一个函数,我们的公司徽标在导出时自动添加到每个图形中,作为函数的一部分,在标题和副标题旁边。每个输出的大小将取决于当时的需求,因此设置一个大小并不是特别有帮助。
为了做到这一点,我已经生成了一系列网格,将所有内容放在一起,如下所示(使用虹膜数据集)。
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))
这将在不同的纵横比下提供以下输出。
第一个例子在标题和副标题之间有一个很好的差距,而第二个例子有太多的差距。我如何才能使TopGrid
的高度固定为绝对大小,而其余的填充到所需的大小?
发布于 2018-02-14 11:08:27
网格图形有绝对单位和相对单位的概念。无论视口大小如何,绝对单位(如"cm“、"in”、"pt")始终保持不变。相对单位(称为"null")根据需要扩展或缩小。在常规ggplot2对象中,绘图面板以相对单位指定,而面板周围的各种元素(如标题、轴刻度等)则以绝对单位指定。
可以使用unit()
函数指定绝对单位或相对单位:
> library(grid)
> unit(1, "cm")
[1] 1cm
> unit(1, "null")
[1] 1null
在您的示例中,grid.arrange
的heights
参数可以接受任意栅格单位对象,因此您只需为顶部高度提供绝对单位:
grid.arrange(TopGrid, arrangeGrob(plot), heights = unit(c(1, 1), c("cm", "null")))
https://stackoverflow.com/questions/48777887
复制相似问题