I am creating following graph on ggplot and need to annotate some info on each graph as subtitle, the graph looks like this:
For title and subtitle purposes, I wrote the following code:
plot.title <- "Link A"
Common <- paste("Percentage:", "10%", sep=" ")
Average <- paste("Average:", "83", sep= " ")
plot.subtitle <- paste(Common, AverageSearchSpace, sep="\n")
and add this in ggplot as:
ggtitle(bquote(atop(.(plot.title), atop(.(plot.subtitle), ""))))
Yet as it can be seen the titles are overlapping currently and i could not find a way to re-position them without overlapping.
I was wondering what the solution to separate the overlapping titles is. I tried to increase the plot margin in theme() with:
theme(plot.margin = unit(c(2, 2, 2, 2), "cm")
However, this did not help.
Also, I tried the following:
plot.title = element_text(size = 85,colour="black", vjust = -2)
This seems to adjust all of the title's position rather than subtitle and title separately.
Also, I could not find any command in theme() such as plot.subtitle to arrange its position. It seems it does not exist.
Any help code piece or related link is appreciated. Thanks.
The position of titles and subtitles is automatically adjusted, however, this positioning clearly fails if titles/subtitles have more than one line and if the size is relatively large, as in your case. So hence the overlap. The easiest way to tackle this, is simply to add an extra (blank) line to your title. Because the title then shifts up, you need to adjust the margins.
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.
There is another option, if you want more control: put only the title or subtitle above the plot with ggtitle
and use annotate
for the other. (please consider that as homework for next week ;-) )