在 ggplot2 中仅更改分面之间的水平间距

32

ggplot2使用opts中的参数panel.margin可以改变分面图之间的边距。这似乎同时更改水平和垂直间距。是否有一种方法只更改水平或垂直间距而不更改另一个间距?

具有结果和期望结果的示例:

mtcars[, c("cyl", "am", "gear")] <- lapply(mtcars[, c("cyl", "am", "gear")], as.factor)

p <- ggplot(mtcars, aes(mpg, wt, group = cyl)) + 
    geom_line(aes(color=cyl)) +
    geom_point(aes(shape=cyl)) + 
    facet_grid(gear ~ am) +
    theme_bw()        

p + opts(panel.margin = unit(1, "lines")) 

目前看起来是这样的:enter image description here

我们如何使它更像这样:enter image description here


我本以为你可以使用上、右、下和左边距的四个参数,但实际上不行。很遗憾。 - Luciano Selzer
1
@lselzer,我也是这么想的,但我认为这个选项只适用于plot.margin。这个功能一年前就有人提出了问题,回答是“目前不可用”。 - A5C1D2H2I1M1N2O1R2T1
自从ggplot2 0.9.2现在用theme替换了opts,并且您可以独立移动某些内容(即panel.grid.major.y等),我想这可能适用于使用:theme(panel.margin.x = unit(1, "lines")),但实际上并不行。 - Tyler Rinker
6
已提交一个问题请求:https://github.com/hadley/ggplot2/issues/678 - Brian Diggs
2个回答

44

截至2015年7月9日,panel.margin.xpanel.margin.y似乎已被实现。

p <- p + theme(panel.margin.x=unit(0.5, "lines") , panel.margin.y=unit(1,"lines"))

截至2016年12月15日,'panel.spacing'和'panel.spacing.x'已在R 3.3.2和ggplot2 2.2.0中实现。

p <- p + theme(panel.spacing.x=unit(0.5, "lines"),panel.spacing.y=unit(1, "lines"))

1
"lines" 是什么意思? - Ben G
1
"lines" 是一个尺寸单位。检查 ?unit,它显示 "lines" 是一个有效的单位,还有 "inches"、"cm" 等。 - AcademicDialysis

9
一个手动解决方案,直到这个功能可用为止:
library(grid)
height <- 0.5 # Vertical spacing
aux <- 1e-5 # Auxiliary number to identify 'height' among other heights
width <- 0.1 # Desirable horizontal spacing

p <- p + theme(panel.margin = unit(height + aux, "lines"))

gtable <- ggplot_gtable(ggplot_build(p))
gtable$widths[sapply(gtable$widths, '[[', 1) == height + aux][[1]][[1]] <- width
grid.draw(gtable)

enter image description here


非常好。希望我们将来能看到它可用。 - Tyler Rinker

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