Add dynamic subtitle using ggplot
Asked Answered
L

1

24

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?

Lapin answered 13/11, 2013 at 15:20 Comment(5)
Use answer of @baptiste of your linked question - just adopt it to latests ggplot2 version - it should work also with variables inside titlesAerify
@DidzisElferts 'opts' is deprecated. Use 'theme' instead. I guess I could use opts but using deprecated stuff seems like a palliative solution. Let's just wait, maybe some others will have other ideas...Lapin
@DidzisElferts I thought i have the latest version please calm down, don't see why you cannot let others suggest ideas...Lapin
@DidzisElferts ok but then give me sometime to try... thanks for all your help btwLapin
Updated answer of @baptiste to previous question, now there won't be warnings about opts()Aerify
A
42

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)), "")))) 

enter image description here

UPDATE - ggplot2 version 2.2.1

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"))
Aerify answered 13/11, 2013 at 15:49 Comment(2)
wow, u re the man! nice answer, nice trick! such an elegant solution, much more elegant than the long themes, opts paradigm :-)Lapin
In order to insert a third-level comment I have modified the code like that: ggplot(mtcars,aes(disp,mpg))+geom_point()+ ggtitle(bquote(atop(.(plot.title), atop(italic(.(plot.subtitle)), "Third title without the possibility to use parameters")))). Is there another way?Splanchnology

© 2022 - 2024 — McMap. All rights reserved.