改变小平面之间的水平间距(ggplot2)

时间:2022-05-28 14:58:59

ggplot2 has the ability to change the margins between a faceted plot using the argument panel.margin in opts. This seems to change both horizontal and vertical spacing. Is there a way to change the spacing of either horizontal or vertical without changing the other?

ggplot2能够使用opts中的参数panel.margin更改多面绘图之间的边距。这似乎改变了水平和垂直间距。有没有办法改变水平或垂直的间距而不改变另一个?

An example with outcome and desired outcome:

结果和期望结果的一个例子:

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")) 

So it currently looks like:改变小平面之间的水平间距(ggplot2)

所以它目前看起来像:

How can we make it look more like:改变小平面之间的水平间距(ggplot2)

我们怎样才能让它看起来更像:

2 个解决方案

#1


18  

As of July 9th, 2015, the panel.margin.x and panel.margin.y seem to have been implemented

截至2015年7月9日,panel.margin.x和panel.margin.y似乎已经实现

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

As of December 15, 2016, 'panel.spacing' and 'panel.spacing.x' is implemented in r 3.3.2 and ggplot2 2.2.0

截至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"))

#2


8  

A manual solution until this feature becomes available:

直到此功能可用的手动解决方案:

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)

改变小平面之间的水平间距(ggplot2)

#1


18  

As of July 9th, 2015, the panel.margin.x and panel.margin.y seem to have been implemented

截至2015年7月9日,panel.margin.x和panel.margin.y似乎已经实现

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

As of December 15, 2016, 'panel.spacing' and 'panel.spacing.x' is implemented in r 3.3.2 and ggplot2 2.2.0

截至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"))

#2


8  

A manual solution until this feature becomes available:

直到此功能可用的手动解决方案:

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)

改变小平面之间的水平间距(ggplot2)