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
510 views
in Technique[技术] by (71.8m points)

r - Specifying ggplot2 panel width

I have two ggplots on the same page, and I'd like their panels to be the same width.

Some sample data:

dfr1 <- data.frame(
  time = 1:10,
  value = runif(10)  
)

dfr2 <- data.frame(
  time = 1:10,
  value = runif(10, 1000, 1001)  
)

One plot below the other:

p1 <- ggplot(dfr1, aes(time, value)) + geom_line()
p2 <- ggplot(dfr2, aes(time, value)) + geom_line()

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))   
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))         
print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))

How do I specify the panel widths and positions in each plot, in order to make them line up?

(I don't want to combine the plots with faceting; it isn't appropriate in my real-world example.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Original solution:

 #   install.packages("ggExtra", repos="http://R-Forge.R-project.org")
 #   library(ggExtra)
 #   align.plots(p1, p2)

Edit (22/03/13):

Since ggExtra doesn't exist anymore (and many internals of ggplot2 have changed), it's better to use the merging functions (rbind, cbind) provided by the gtable package,

gl = lapply(list(p1,p2), ggplotGrob)     
library(gtable)
g = do.call(rbind, c(gl, size="first"))
g$widths = do.call(unit.pmax, lapply(gl, "[[", "widths"))

grid.newpage()
grid.draw(g)    

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

...