Specifying ggplot2 panel width

岁酱吖の 提交于 2019-11-26 09:43:19

问题


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


回答1:


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)    



来源:https://stackoverflow.com/questions/5489250/specifying-ggplot2-panel-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!