At the end of a ggplot, this works fine:
+ opts(title = expression("Chart chart_title..."))
But this does not:
chart_title = "foo"
+ opts(title = expression(chart_title))
nor this:
chart_title = "foo"
+ opts(title = chart_title)
How can I add a title to a ggplot when the title is a variable name?
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.