I am trying to use ggplot to add a subtitle. Similar question was asked here: How to add a ggplot2 subtitle with different size and colour?, and the answer was as follows:
p <- p + ggtitle(expression(atop(paste('TITLE'), atop(italic(paste('SUBTITLE')), ""))))
However, the words 'TITLE'
and 'SUBTITLE'
need to be hardcoded, presenting an scalability and automation problem when dealing with 1000s of plots.
This does not work:
plot.title = 'TITLE' plot.subtitle = 'SUBTITLE' p <- p + ggtitle(expression(atop(paste(plot.title), atop(italic(paste(plot.subtitle)), ""))))
I guess the question on how to proper add dynamic subtitles, using this idea, boils down to: Is it possible to use character variables inside expression and atop?
You should use function bquote()
instead of expression()
to use titles that are stored as variables. And variable names should be placed inside .()
plot.title = 'TITLE' plot.subtitle = 'SUBTITLE' ggplot(mtcars,aes(disp,mpg))+geom_point()+ ggtitle(bquote(atop(.(plot.title), atop(italic(.(plot.subtitle)), ""))))
The latest ggplot2 version now can produce subtitles directly, so you don't have to use bquote()
and expression()
. The result is atchieved with argument subtitle =
of function labs()
.
ggplot(mtcars,aes(disp,mpg))+geom_point()+ labs(title = plot.title,subtitle = plot.subtitle) + theme(plot.subtitle = element_text(face = "italic"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With