ggplot 副标题和标题位置 - 重叠标题

ggplot subtitle and title position - overlapping titles

我正在 ggplot 上创建以下图表,需要在每个图表上注释一些信息作为副标题,图表如下所示: 为了标题和副标题的目的,我写了下面的代码:

plot.title <- "Link A" 
Common <- paste("Percentage:", "10%", sep=" ")
Average <- paste("Average:", "83", sep= " ")
plot.subtitle <- paste(Common, AverageSearchSpace, sep="\n")

并将其添加到 ggplot 中:

ggtitle(bquote(atop(.(plot.title), atop(.(plot.subtitle), "")))) 

然而,正如可以看到的那样,标题目前是重叠的,我找不到 re-position 它们不重叠的方法。

我想知道分离重叠标题的解决方案是什么。我试图通过以下方式增加 theme() 中的情节边距:

theme(plot.margin = unit(c(2, 2, 2, 2), "cm")

然而,这并没有帮助。

此外,我尝试了以下方法:

plot.title = element_text(size = 85,colour="black", vjust = -2)

这似乎调整了所有标题的位置,而不是单独调整副标题和标题。

此外,我在 theme() 中找不到任何命令,例如 plot.subtitle 来安排它的位置。好像不存在

任何帮助代码片段或相关 link 表示赞赏。谢谢。

你可以使用这个技巧

require(ggplot2)
require(gridExtra) # tableGrob

element_grob.element_custom <- function(element, label="", ...)  {

  mytheme <- ttheme_minimal(colhead = list(fg_params = list(parse=TRUE, fontsize = 16)),
                            core = list(fg_params = list(parse=TRUE)))
  disect <- strsplit(label, "\n")[[1]]
  m <- as.matrix(disect[-1])
  g1 <- tableGrob(m, cols = disect[1], theme=mytheme)
  # wrapping into a gTree only because grobHeight.gtable would be too tight
  # cf. absolute.units() squashing textGrobs
  gTree(children=gList(g1), height=sum(g1$heights), 
        cl = "element_custom")
}

# gTrees don't know their size 
grobHeight.element_custom = heightDetails.element_custom = function(x, ...)
  x$height
# silly wrapper to fool ggplot2's inheritance check...
element_custom <- function() {
  structure(list(), class = c("element_custom", "element_text"))
}

title <- c("First~line \n italic('wait, a second')\n integral(f(x)*dx, a, b)")


ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_line() + ggtitle(title) +
  (theme_grey() %+replace% theme(plot.title  = element_custom()))

标题和副标题的位置是自动调整的,但是,如果titles/subtitles多行并且尺寸相对较大(如您的情况),则此定位显然会失败。因此重叠。 解决这个问题的最简单方法就是在您的标题中添加一个额外的(空白)行。因为标题会上移,所以需要调整页边距。

library(ggplot2)
library(grid)
#first some toy data, next time please provide some yourself!
data <- data.frame(x=5*rep(1:100,each=5),type=rep(c("BM1","BM2","BM3","NB1","NB2"),20),y=10*(2+rnorm(500)))

plot.title <- "Link A\n" # added an extra line here 
Common <- paste("Percentage:", "10%", sep=" ")
Average <- paste("Average:", "83", sep= " ")
plot.subtitle <- paste(Common, Average, sep="\n")
plot.tottitle <- paste(plot.title,Common, Average, sep="\n")

ggplot(data,aes(x=x,y=y,color=type))+
  geom_line() + ggtitle(bquote(atop(.(plot.title), atop(.(plot.subtitle), ""))))  + 
  theme(plot.title = element_text(size = 50,colour="black", vjust = 0)) +
  theme(plot.margin = unit(c(2, 0, 0, 0), "cm")) #margin adjusted because title moves off plot.

结果图片:

如果您想要更多控制,还有另一种选择:使用 ggtitle 仅将标题或副标题放在图的上方,另一个使用 annotate。 (请将其视为下周的作业 ;-))