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

8
我需要将多个图表依次放置在一起,并且希望边缘和图形区域的宽度相同,以便它们能够整齐地对齐。请注意,我需要两个单独的图表,而不是一个联合图表。我想将每个图表保存在单独的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 中如何实现这一点?


请参见以下链接的评论:http://stackoverflow.com/questions/41230345/ggplot2-change-plot-areas-for-same-size-plots-in-multiplot#comment69662588_41230345 - user20650
https://github.com/baptiste/egg#setting-panel-size - baptiste
1个回答

6
根据上面评论中最后一个链接的回答,您可以使图形的宽度相等。与该回答唯一的不同之处在于它们没有合并。
因此,对于您的图形:
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

enter image description here

图表2

enter image description here


非常好,谢谢!这里关键是宽度。你是否有一个好的参考来了解ggplot图形区域的结构,就像这个基础图形的参考一样:http://www.melissaclarkson.com/resources/R_guides/documents/figure_layout_Ver1.pdf - Mark Heckmann
@MarkHeckmann;Baptiste确实是帮助解决这个问题的人。但也许他的egg package中的expose_layout会很有用。所以使用p1 <- qplot(mpg, wt, data=mtcars, colour=cyl) + ggtitle("facetted plot");g = expose_layout(p1);g$widths。然后看看宽度与暴露的布局图对齐的情况。(宽度从左到右)(还要查看names(g)以检查其他内容)。 - user20650

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接