显示ggplot2标题而不为其保留空间

时间:2015-05-27 20:23:05

标签: r ggplot2

我正在尝试将标题设置为某些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)

plot sample

我不能在其他情节上使用假空字符串标题,因为我空间不足。 我可以使用geom_text()方法,如果有人能告诉我如何使它看起来不那么乱码。 那么,如何删除绘图区域上方标题的任何预留空间,同时仍然在绘图区域的顶部和顶部显示绘图标题?后者使用theme(plot.title = element_text(vjust=-1))完成。)

2 个答案:

答案 0 :(得分:3)

修改 感谢@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)

enter image description here

如果您愿意,可以使用标题的vjust设置将其移出绘图或进一步移动到绘图上:

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

enter image description here

答案 1 :(得分:2)

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

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

是一种很好的做法。注释也可用于向绘图添加单个水平或垂直线,或通过在其周围绘制矩形来突出显示区域。