【问题标题】:Aligning / setting width of margin/figure region in ggplot2在ggplot2中对齐/设置边距/图形区域的宽度
【发布时间】:2016-12-20 20:54:42
【问题描述】:

我需要将多个图放置在彼此下方,并且我希望边距和图形区域的宽度相同,以便它们整齐地对齐。请注意,我需要两个单独的地块,而不是一个联合地块。我想将每个文件保存在一个单独的 PNG 文件中。我只希望它们的结构(边距、图形区域大小)相同。

library(ggplot2)

d <- data.frame(label=c("some very longe label with lots of text", 
                        "another long label with lots of text", 
                        "short", 
                        "also short",
                        "                                     short", 
                        "                                also short"), 
                        x = 1:6)

ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()
ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()

我想要的是情节 2 具有与情节 1 中相同的左边距宽度,或多或少如下所示,当然不添加额外的空白;)

在基本图形中,我将相应地设置par("mar")。

如何在 ggplot 中实现这一点?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

根据last link from the comment above的回答, 您可以使绘图的宽度相等。与该答案的唯一区别是它们没有合并。

所以对于你的情节

library(ggplot2)
p1 <- ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()
p2 <- ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()

绘图宽度相等

library(grid)
gl <- lapply(list(p1,p2), ggplotGrob)  
wd <- do.call(unit.pmax, lapply(gl, "[[", 'widths'))
gl <- lapply(gl, function(x) {
        x[['widths']] = wd
        x})

剧情

grid.newpage(); grid.draw(gl[[1]])
grid.newpage(); grid.draw(gl[[2]])

产生:

情节 1

情节 2

【讨论】:

  • 太好了,谢谢!宽度是这里的关键。您是否对 ggplot 图形区域的结构有很好的参考,例如基本图形:melissaclarkson.com/resources/R_guides/documents/…
  • @MarkHeckmann ;巴蒂斯特真的是帮助解决这个问题的人。但也许他的egg package 中的expose_layout 会很有用。所以使用 p1 &lt;- qplot(mpg, wt, data=mtcars, colour=cyl) + ggtitle("facetted plot") ; g = expose_layout(p1) ; g$widths 。然后看看宽度如何与暴露的布局图对齐。 (宽度从左到右)(另请查看names(g) 以了解其他要检查的内容)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
相关资源
最近更新 更多