2012-01-17 23 views
11

我用下面的代碼驚人的包GGPLOT2打造三套地塊:grid.layout在ggplot

w<-rnorm(100) 
x<-rnorm(100) 
y<-rnorm(100) 
z<-rnorm(100) 
g<-rep(factor(LETTERS[1:4]), 25) 
d<-data.frame(g,w,x,y,z) 

library(ggplot2) 

pw<-ggplot(d, aes(w, y)) 
px<-ggplot(d, aes(x, y)) 
pz<-ggplot(d, aes(z, y)) 

pw+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm') 
px+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm') 
pz+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm') 

我會讓有這三個組地塊打印的PDF文件在同一頁上。我的理解是split.screen(c(3,1))par(mfrow=c(3,1))不會GGPLOT2圖形工作,但grid.layout()從格包會的工作,所以我嘗試:

pdf(file="test.pdf") 
pushViewport(viewport(layout=grid.layout(3,1))) 
print(pw+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm')) 
print(px+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm')) 
print(pz+geom_point()+facet_grid(.~g, scales='fixed')+coord_equal()+stat_smooth(method='lm')) 
dev.off() 

但這最終是與第一頁是一個四頁的PDF文件空白,每一組數字在每頁之後顯示一個,x軸標籤在底部顯示。有沒有辦法在同一頁面上製作一個包含所有圖形的PDF文件(並且沒有空白頁面導致!)?

+4

'ggplot2 ::: print.ggplot'有一個'vp'參數來指定可選的視口;如果留下'NULL',ggplot2會調用'grid.newpage()'(除非你用'newpage = FALSE'告訴它不要)並使用整個頁面(默認視口)。您需要使用'print(p,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))'將佈局放置在佈局中。 – baptiste 2012-01-17 19:17:10

+0

完美!這正是我想要的(很明顯,將'layout.pos.row'更改爲2和3以獲得後續圖表。謝謝! – smillig 2012-01-17 19:35:31

回答

20

你可能要使用grid.arrange()一個更好的時間,從gridExtra包:

p1 <- pw + geom_point() + facet_grid(.~g, scales='fixed') + coord_equal() + 
     stat_smooth(method='lm') 
p2 <- px + geom_point() + facet_grid(.~g, scales='fixed') + coord_equal() + 
     stat_smooth(method='lm') 
p3 <- pz + geom_point() + facet_grid(.~g, scales='fixed') + coord_equal() + 
     stat_smooth(method='lm') 

grid.arrange(p1, p2, p3, ncol=1) 

enter image description here

+0

此替代方案完美地工作!謝謝! – smillig 2012-01-17 19:36:06

+0

嗨,我怎樣才能指定p1,p2的高度,網格中的p3? – neoFox 2017-01-17 09:28:56

1

如果您使用markdown,請在每個代碼塊中爲每個繪圖使用fig.height

```{r pw, fig.height = 2.66, echo = F} 
pw 
``` 
```{r px, fig.height = 2.66, echo = F} 
px 
``` 
```{r pz, fig.height = 2.66, echo = F} 
pz 
```