【问题标题】:Add space between specific facets in ggplot2 (facet_grid)在 ggplot2 (facet_grid) 中的特定方面之间添加空间
【发布时间】:2018-08-13 20:23:25
【问题描述】:

我已经能够在所有构面之间添加垂直空间 (Alter just horizontal spacing between facets (ggplot2)),但无法在指定构面之间仅添加一个空间?

这是一个基于我的真实数据的示例(在真实图中我有堆积条):

mydf<-data.frame(year = rep(c(2016,2016,2016,2016,2016,2016,2017,2017,2017,2017,2017,2017),times = 2),
             Area = rep(c('here','there'),times = 12),
             yearArea = rep(c('here.2016','here.2017', 'there.2016','there.2017'), times = 12),
             treatment = rep(c('control','control','control','treat', 'treat','treat'), times = 4),
             response = rep(c('a','b','c','d'), times = 6),
             count = rep(c(23,15,30,20), times = 6))
mycolour<-c("#999999", "#0072B2", "#009E73","#000000")

返回情节:

#default facet spacing 
example<-ggplot(data=mydf, aes(x=treatment, y=count, fill=response)) + 
  geom_bar(stat="identity", width = 0.5) +  
  scale_fill_manual(values = mycolour, name = "Response") + 
  labs (y = "Count") +
  facet_grid(~yearArea) + 
  theme_bw()
example

#spacing between each facet
spacedex<-example + theme(panel.spacing.x=unit(2, "lines"))

spacedex

如何将添加的空间限制为仅在第二个和第三个方面之间? (here.2017 和 there.2016 之间)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:
    library(grid)
    gt = ggplot_gtable(ggplot_build(example))
    gt$widths[7] = 4*gt$widths[7]
    grid.draw(gt)
    

    【讨论】:

    • 感谢您的回答,但您能简要解释一下这段代码中发生了什么吗?我无法使用 mtcars 数据集复制相同的内容。
    • 我明天可以添加更多信息。现在需要睡觉了。基本上,您需要找出 gt$widths 中的哪个宽度对应于您要更改的宽度(在本例中是数字 7)。同时,阅读有关网格和网格布局的信息,您可能会在我回过头来之前弄明白。
    • @Ashish,如果你玩这两个数字,[7] 是间距的位置,4* 是间距的宽度
    • @dww,根据建议,我想出了另一个优雅的解决方案。要扩展网格中的垂直和水平间距,请在theme() 中使用panel.spacing。要仅扩展网格中列之间的垂直间距,请使用panel.spacing.x,而仅扩展网格中行之间的水平间距,请使用theme() 中的panel.spacing.y。谢谢@Emily 的解释。
    • 感谢@dww 的回答。我还试图弄清楚如何找到正确的元素进行编辑。我试图找到 gtable 结构的详细解释,但只能在cran.r-project.org/web/packages/gridExtra/vignettes/gtable.html 找到一个简短的(且不完整的)介绍,这并没有达到我需要的深度。如果您能为此提供参考,我将不胜感激。