指定 ggplot2 面板宽度 [英] Specifying ggplot2 panel width
本文介绍了指定 ggplot2 面板宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在同一页面上有两个 ggplots,我希望它们的面板宽度相同.
I have two ggplots on the same page, and I'd like their panels to be the same width.
一些示例数据:
dfr1 <- data.frame(
time = 1:10,
value = runif(10)
)
dfr2 <- data.frame(
time = 1:10,
value = runif(10, 1000, 1001)
)
一个图在另一个下面:
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.)
推荐答案
原解决方案:
# install.packages("ggExtra", repos="http://R-Forge.R-project.org")
# library(ggExtra)
# align.plots(p1, p2)
编辑 (22/03/13):
Edit (22/03/13):
由于ggExtra已经不存在了(并且ggplot2的很多内部结构都发生了变化),最好使用gtable包提供的合并函数(rbind,cbind),
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)
这篇关于指定 ggplot2 面板宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文