【问题标题】:Arrange multiple ggplots with same plot width but different plot height [duplicate]排列多个具有相同绘图宽度但不同绘图高度的ggplots [重复]
【发布时间】:2015-05-18 16:41:28
【问题描述】:

我尝试使用 gridExtra 包排列两个具有不同绘图高度但绘图宽度相同的 ggplots。

我有一个相同宽度或相同高度的解决方案,但我无法同时实现。

这是我的代码:

require(ggplot2)
require(gridExtra)

set.seed(987)
dat <- data.frame(x = 1:100, 
              y1 = rnorm(100),
              y2 = rnorm(100)*1e6)

p1 <- ggplot(dat, aes(x = x, y = y1)) + 
  geom_point() + ylab("")

p2 <- ggplot(dat, aes(x = x, y = y2)) + 
  geom_point() + ylab("")

# Arrange Plots

# Version 1
# same widths, same heights
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))

# Version 2
# different heights, different widths
grid.arrange(p1, p2, ncol = 1, heights = c(2, 1)) 

结果如下:

版本 1:宽度相同但高度不同

版本 2:不同的高度但不同的绘图宽度

但是,我想要组合:相同的宽度,但不同的高度。您对在这种情况下如何组合 grid.draw 和 grid.arrange 有任何想法吗?

【问题讨论】:

标签: r ggplot2 gridextra


【解决方案1】:

感谢@Gregor 和他对这个questions 的链接,我可以使用其他问题的大部分代码并进行一些小的改动。这就是它最终的样子:

gb1 <- ggplot_build(p1)
gb2 <- ggplot_build(p2)
# work out how many y breaks for each plot
n1 <- length(gb1$panel$ranges[[1]]$y.labels)
n2 <- length(gb2$panel$ranges[[1]]$y.labels)

gA <- ggplot_gtable(gb1)
gB <- ggplot_gtable(gb2)

# combine both plots (last should really be "pmax", it's an unfortunate bug)
g <- gtable:::rbind_gtable(gA, gB, "last")

# locate the panels in the gtable layout
panels <- g$layout$t[grepl("panel", g$layout$name)]
# assign new (relative) heights to the panels, based on the number of breaks
g$heights[panels] <- list(unit(n1*2,"null"), unit(n2, "null")) 
# notice the *2 here to get different heights 

grid.newpage()
grid.draw(g)

【讨论】:

  • 我试图在三个地块上实现这个,但是没有用?应该这样吗?
  • 我只用了两个,从来没有尝试过更多。
  • 它似乎不适用于两个以上
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
相关资源
最近更新 更多