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?

Community
  • 1
  • 1
Dnaiel
  • 7,622
  • 23
  • 67
  • 126
  • Use answer of @baptiste of your linked question - just adopt it to latests ggplot2 version - it should work also with variables inside titles – Didzis Elferts Nov 13 '13 at 15:23
  • 1
    @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... – Dnaiel Nov 13 '13 at 15:26
  • @DidzisElferts I thought i have the latest version please calm down, don't see why you cannot let others suggest ideas... – Dnaiel Nov 13 '13 at 15:28
  • @DidzisElferts ok but then give me sometime to try... thanks for all your help btw – Dnaiel Nov 13 '13 at 15:30
  • 1
    Updated answer of @baptiste to previous question, now there won't be warnings about opts() – Didzis Elferts Nov 13 '13 at 15:35

1 Answers1

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"))
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 1
    wow, u re the man! nice answer, nice trick! such an elegant solution, much more elegant than the long themes, opts paradigm :-) – Dnaiel Nov 13 '13 at 16:33
  • 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? – Andrea Ianni Apr 18 '16 at 09:57