在ggplot2中对齐/设置边距/图形区域的宽度

Mar*_*ann 7 r ggplot2

我需要在彼此之下放置几个图,我希望边距和图形区域的宽度相同,因此它们整齐排列.请注意,我需要两个单独的图,而不是一个联合图.我想将每个保存在一个单独的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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

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

在此输入图像描述

在基本图形中,我只是相应地设置par("mar").

我怎样才能在ggplot中实现这一目标?

use*_*650 5

根据上面评论最后一个链接的答案,您可以将图的宽度等同起来.与答案的唯一区别是它们没有合并.

所以对你的情节

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()
Run Code Online (Sandbox Code Playgroud)

等于图的宽度

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})
Run Code Online (Sandbox Code Playgroud)

情节

grid.newpage(); grid.draw(gl[[1]])
grid.newpage(); grid.draw(gl[[2]])
Run Code Online (Sandbox Code Playgroud)

哪个产生:

情节1

在此输入图像描述

情节2

在此输入图像描述