How to add a title to a ggplot when the title is a variable name?

Opts is being deprecated. One option is to use labs()

myTitle <- "My title"
qplot(mpg, wt, data = mtcars) + labs(title = myTitle)

Pretty much the same.


As others pointed out, your example seems to work fine for the cases where the variable chart_title is a string or an expression. Sometimes it's tricky to construct the title variable; for instance, a confusing scenario might arise if chart_title uses some other variables, and if in addition you are using some greek characters so a simple paste(...) doesn't suffice. To construct a title like that, you could use something like the following:

foo <- rnorm(100)
number <- 1
chart_title <- substitute(paste("Chart no. ",number,": ",alpha," vs ",beta,sep=""), list(number = number))
qplot(foo,foo) + opts(title = chart_title)

Another function that comes in handy when constructing titles is bquote(). Programmatic title construction can be a messy business; R FAQ 7.13 (http://cran.r-project.org/doc/FAQ/R-FAQ.html) can get you started, but even that FAQ basically tells you to search R-Help when in doubt.


Please provide a reproducible example. The following works fine for me:

title <- "My title"
qplot(mpg, wt, data = mtcars) + opts(title = title)

Since version 0.9.2, opts has been replace by theme:

qplot(mpg, wt, data = mtcars) + theme(title = title)

Also, see ?ggtitle.

Tags:

R

Title

Ggplot2