Reputation: 5249
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?
Upvotes: 43
Views: 75069
Reputation: 470
ggtitle( paste( "The sum is =", mysum, "The Count is =", N ) )
mysum and N are variables
Upvotes: 4
Reputation: 103948
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
.
Upvotes: 15
Reputation: 1070
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.
Upvotes: 30
Reputation: 13493
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.
Upvotes: 26