接受的答案是最直接和最簡單的方式來實現所需的輸出,但我用這個問題作爲了解更多關於使用grobs的機會,我想我會分享我學到的東西。
要修改facet標籤之間的間距,我們可以操作底層的grobs。要做到這一點,首先生成劇情grob:
library(ggplot2)
library(grid)
p <- ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~ cyl + drv)
g <- ggplotGrob(p)
現在,我們可以檢查grobs。刻面帶是grobs 47〜55(9 grobs),我們注意到,每個條GROB實際上是grobs的一個表:
g
# TableGrob (21 x 15) "layout": 62 grobs
# z cells name grob
# 1 0 (1-21, 1-15) background rect[plot.background..rect.614]
# 2 1 (7- 7, 4- 4) panel-1-1 gTree[panel-1.gTree.33]
# 3 1 (12-12, 4- 4) panel-2-1 gTree[panel-4.gTree.78]
# ...
# 47 2 (16-16, 4- 4) strip-t-1-3 gtable[strip]
# 48 2 (16-16, 8- 8) strip-t-2-3 gtable[strip]
# 49 2 (16-16,12-12) strip-t-3-3 gtable[strip]
# 50 2 (11-11, 4- 4) strip-t-1-2 gtable[strip]
# 51 2 (11-11, 8- 8) strip-t-2-2 gtable[strip]
# 52 2 (11-11,12-12) strip-t-3-2 gtable[strip]
# 53 2 (6- 6, 4- 4) strip-t-1-1 gtable[strip]
# 54 2 (6- 6, 8- 8) strip-t-2-1 gtable[strip]
# 55 2 (6- 6,12-12) strip-t-3-1 gtable[strip]
# 56 4 (4- 4, 4-12) xlab-t zeroGrob[NULL]
# ...
着眼於GROB 47,我們可以深入到結構...
str(g$grobs[[47]], m = 1)
str(g$grobs[[47]]$grobs, m = 1)
str(g$grobs[[47]]$grobs[[1]], m = 1)
str(g$grobs[[47]]$grobs[[1]]$children, m = 1)
str(g$grobs[[47]]$grobs[[1]]$children[[2]], m = 1)
str(g$grobs[[47]]$grobs[[1]]$children[[2]]$children, m = 1)
......直到我們找到了如何在小標籤被指定:
str(g$grobs[[47]]$grobs[[1]]$children[[2]]$children[[1]], m = 1)
# List of 11
# $ label : chr "8"
# $ x :Class 'unit' atomic [1:1] 0.5
# .. ..- attr(*, "valid.unit")= int 0
# .. ..- attr(*, "unit")= chr "npc"
# $ y :Class 'unit' atomic [1:1] 0.5
# .. ..- attr(*, "valid.unit")= int 0
# .. ..- attr(*, "unit")= chr "npc"
# $ just : chr "centre"
# $ hjust : NULL
# $ vjust : NULL
# $ rot : num 0
# $ check.overlap: logi FALSE
# $ name : chr "GRID.text.322"
# $ gp :List of 6
# ..- attr(*, "class")= chr "gpar"
# $ vp : NULL
# - attr(*, "class")= chr [1:3] "text" "grob" "gDesc"
現在,我們只要改變價值y
,這樣的頂級GROB標籤是NEA在底部,並且底部grob的標籤靠近頂部。我這樣做只在最左邊的列中的小條,使我們可以看到其中的差別:
for (i in c(47, 50, 53)) {
g$grobs[[i]]$grobs[[1]]$children[[2]]$children[[1]]$y = unit(0.1, "npc")
g$grobs[[i]]$grobs[[2]]$children[[2]]$children[[1]]$y = unit(0.9, "npc")
}
grid.newpage()
grid.draw(g)
輸出: