给facet_wrap图表添加另一个ggplot或注释

3
我有一个相当复杂的facet_wrap区域,其中包含共享公共图例的分级地图,并将它们分成单独的绘图区域。我想在未使用的facet区域中添加另一个非常简单的条形图。我认为我可以使用annotation_custom,如下所示:https://github.com/hadley/ggplot2/wiki/Mixing-ggplot2-graphs-with-other-graphical-output
p = qplot(1:10, 1:10) + theme_bw()
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 2, xmax = 7, ymin = 6, ymax = 10)

但是,即使调整x/y的最小/最大值,似乎也无法正确地调整大小。它似乎想在每个面上注释。这不是我想要的。

将每个面分开成单独的图,并使用gridExtra::grid.arrange会很困难,因为每个面共同生成一个共享渐变图例。

plot1 <- ggplot(mtcars, aes(factor(mtcars$gear))) + 
    geom_bar() + 
    facet_wrap(~cyl, ncol=2) + 
    coord_flip()


plot2 <- ggplot(mtcars, aes(as.factor(am))) + 
    geom_bar(aes(fill=factor(cyl)))

以下的绘图会失败(在每个分面上绘制):

g <- ggplotGrob(plot2)

plot1 + annotation_custom(grob = g, xmin = 0, xmax = 1, ymin = 0, ymax = 1)

期望的外观:

在此输入图片描述

1个回答

10
g1 <- ggplotGrob(plot1)
g2 <- ggplotGrob(plot2)

g1 <- gtable::gtable_add_grob(g1, g2, t = 8, l=7)
grid.newpage()
grid.draw(g1)

+1000!我曾尝试使用ggplot_gtable来解决这个问题,但这种方法更加优雅简洁(比我的方法更易读)。 - hrbrmstr
1
@batiste 好极了。我的实际问题是5个面(2列)加一个空面的包装。我阅读了gtable_add_grob的文档,但无法弄清楚tl在做什么。对于我的情况,我使用了t = 12,l = 7,但这些信息可能对未来的搜索者有所帮助。 - Tyler Rinker
3
您可以在此处查看相关的问答,使用tl的略有不同的替代用法,避免硬编码。请注意,本翻译不包含解释或其他内容。 - Henrik

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