编辑ggplot2条形图大小

19
我曾经尝试使用这个解决方案(如何在ggplot中更改facet上条带的大小?1)来更改 ggplot 中 facets 上条带的大小,我已经增加了高度大小。
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)

这就是我得到的结果,它只会增加条带顶部的空白部分 (白色): 在此输入图片描述

为什么它的工作方式不同呢?


3
ggplot2 的较新版本已经重新设计了分面系统,因此这不再起作用。 - Axeman
2个回答

38
一个简单的解决方案是适当指定你的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")))

在此输入图片描述


3

这样的代码似乎可以工作:

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


谢谢。所以,基本上 g$heights[[6]] <- unit(5,"in") 移动了条带,而 g$grobs[[17]]$heights <- unit(2,"in") 扩大了条带区域。但我看不出单位之间的关联。 - Al14
1
没错。看起来单位有点奇怪,因为在分配英寸后 g$heights[[6]] 给出了 5cm。我只是随便试了一下。 - Axeman
1
网格单位没有 [[<- 方法。最近才引入了 [<- 的方法,但请注意它会将结果强制转换为 unit.list - baptiste

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