Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dynamic subtitle using ggplot

Tags:

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?

like image 635
Dnaiel Avatar asked Nov 13 '13 15:11

Dnaiel


1 Answers

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")) 
like image 151
Didzis Elferts Avatar answered Oct 06 '22 23:10

Didzis Elferts