2012-09-03 103 views
17

ggplot2可以使用參數panel.marginopts更改刻面圖之間的邊距。這似乎改變了水平和垂直間距。有沒有辦法改變水平或垂直的間距而不改變其他的?改變刻面之間的水平間距(ggplot2)

與結果和預期的結果的一個例子:

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

+0

我早就猜到你可以使用四個參數爲上,右,底部和左側空白,但你不能。遊民。 –

+1

@lselzer,我也這麼認爲,但我認爲這個選項只適用於'plot.margin'。該功能一年前被問及(https://groups.google.com/d/topic/ggplot2/tMQsVb5P69s/discussion),其可用性的答案是「目前不是」。 – A5C1D2H2I1M1N2O1R2T1

+0

由於ggplot2 0.9.2現在用'theme'替換'opts',並且可以移動一些獨立於另一個的東西(即'panel.grid.major.y'等),所以我想這可能會使用:'theme(panel .margin.x = unit(1,「lines」))'但它沒有。 –

回答

18

隨着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")) 
+0

美麗。剛剛使用它。 –

8

手動解決方案,直到此功能變爲可用:

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

+0

非常好。希望我們在未來看到這一點。 –