显示 ggplot2 标题而不为其保留 space

show ggplot2 title without reserving space for it

我正在尝试为一些 ggplot2 图表设置标题,同时让一些图表没有标题。不幸的是,设置标题后,y 轴和绘图会缩小(见右图)。我需要在不改变 Y 轴大小的情况下绘制标题,以便带标题的图表与其他图表的比例相同(如中间图所示)。

grid.arrange(
  (ggplot(mtcars, aes(mpg, hp)) + geom_point()),
  (ggplot(mtcars, aes(mpg, hp)) + geom_point() + 
    geom_text(aes(22.5, 340, label="fake title",  vjust = 1, hjust = .5, show_guide = FALSE))),
  (ggplot(mtcars, aes(mpg, hp)) + geom_point() +
    labs(title="real title")),
  ncol=3)

我不能在其他地块上使用假 empty-string 标题,因为我 space 很短。 我可以使用 geom_text() 方法,如果有人能告诉我如何让它看起来不那么乱码的话。 那么,如何删除绘图上方标题的任何保留 space,同时仍然在绘图区域上和顶部显示绘图标题?后者是用 theme(plot.title = element_text(vjust=-1)).)

完成的

编辑 感谢@baptiste 指出了一种更简洁的方法来完成此任务。从下面给出 p1p2p3

pl = lapply(list(p1,p2,p3), ggplotGrob)
grid.newpage()
grid.draw(do.call(cbind, c(pl, size="first")))

原回答

您可以构建 ggplot grobs 并跨地块标准化 heights 参数:

p1 <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + labs(title="real title")
p3 <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + 
    geom_text(aes(22.5, 340, label="fake title",  vjust = 1, hjust = .5, show_guide = FALSE))

p1 <- ggplot_gtable(ggplot_build(p1))
p2 <- ggplot_gtable(ggplot_build(p2))
p3 <- ggplot_gtable(ggplot_build(p3))

p2$heights <- p1$heights
p3$heights <- p1$heights

grid.arrange(p1, p2, p3, ncol=3)

然后,如果需要,您可以使用标题的 vjust 设置将其移出剧情或进一步移到剧情上:

p2 <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + 
    labs(title="real title") + 
    theme(plot.title=element_text(vjust=-.3))

您应该为此使用 annotate。如果您使用 geom_text,它将打印与数据中的行一样多的标签,因此您的问题中看起来很糟糕的 overplotted 标签。一个痛苦的解决方法是创建一个 1 行数据框用作 geom_text 层的数据。但是,annotate 是为这类事情而设计的,因此您不需要解决方法。类似于:

 annotate(geom = "text", x = 22.5, y = 340, label="fake title")

是个好习惯。注释对于向绘图添加单条水平线或垂直线,或通过在区域周围绘制矩形来突出显示区域也很有用。