Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

r - grid.layout in ggplot

I'm using the following code to create three sets of plots in the amazing package ggplot2:

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

I would make a PDF file that has each of these three sets of plots printed on the same page. My understanding is thatsplit.screen(c(3,1))andpar(mfrow=c(3,1))won't work with ggplot2 graphics, but thatgrid.layout()from the grid package would work so I tried:

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

but this ends up being a four page PDF file with the first page being blank and each set of figures following one per page and the x-axis label way down at the bottom. Is there a way to make a PDF file with all the sets of figures on the same page (and without a blank page leading!)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll probably have a better time using grid.arrange(), from the gridExtra package:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...