2017-01-02 62 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