2017-01-02 58 views
6

我試圖將此溶液(How can I change the size of the strip on facets in a ggplot?1)在ggplot更改條帶大小的面,我有增加高度尺寸編輯條帶大小GGPLOT2

library(ggplot2) 
library(gtable) 

d <- ggplot(mtcars, aes(x=gear)) + 
      geom_bar(aes(y=gear), stat="identity", position="dodge") + 
      facet_wrap(~cyl) 

g <- ggplotGrob(d) 
g$heights[[3]] = unit(5,"in") 

grid.newpage() 
grid.draw(g) 

這是我得到的,它只會增加條帶頂部的空間(白色): enter image description here

爲什麼它的工作方式不同?

+1

較新版本的ggplot2 '有一個徹底改變的方面系統,這就是爲什麼這不再起作用。 – Axeman

回答

14

一個簡單的解決方法是適當地確定你的strip.text元素的邊距:

ggplot(mtcars, aes(x=gear)) + 
    geom_bar(aes(y=gear), stat="identity", position="dodge") + 
    facet_wrap(~cyl) + 
    theme(strip.text.x = element_text(margin = margin(2,0,2,0, "cm"))) 

enter image description here

2

像這樣的事情似乎工作:

g$heights[[6]] <- unit(5,"in") 
g$grobs[[17]]$heights <- unit(2,"in") 
g$grobs[[18]]$heights <- unit(2,"in") 
g$grobs[[19]]$heights <- unit(2,"in") 

grid.newpage() 
grid.draw(g) 

注意看g$grobs告訴我們grobs 17,18和19條。

您可以自動進行第二步:

index <- which(sapply(g$grobs, function(x) x$name == "strip")) 
g$grobs <- lapply(seq_along(g$grobs), function(.x) { 
    if(.x %in% index) { 
    g$grobs[[.x]]$heights <- unit(2,"in") 
    } 
    g$grobs[[.x]] 
}) 

enter image description here

+0

謝謝。因此,基本上'g $ heights [[6]] < - unit(5,「in」)'移動條帶,而'g $ grobs [[17]] $ heights < - unit(2,「in」)'擴大帶區域。但我看不到單位之間的相關性 – Al14

+1

這是正確的。看起來單位有點奇怪,因爲'g $ heights [[6]]'在分配英寸後給出了'5cm'。我只是玩了一下。 – Axeman

+1

沒有'[[< - '格子單位的方法。直到最近才引入了'[< - ',但它注意到它將結果強制轉換爲'unit.list'。 – baptiste