Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

r - Add dynamic subtitle using ggplot

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...