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

后端 未结 4 1198
再見小時候
再見小時候 2020-12-23 13:41

At the end of a ggplot, this works fine:

+ opts(title = expression(\"Chart chart_title...\"))

But this does not:

chart_titl         


        
相关标签:
4条回答
  • 2020-12-23 14:21

    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.

    0 讨论(0)
  • 2020-12-23 14:27

    ggtitle( paste( "The sum is =", mysum, "The Count is =", N ) )

    mysum and N are variables

    0 讨论(0)
  • 2020-12-23 14:30

    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.

    0 讨论(0)
  • 2020-12-23 14:43

    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.

    0 讨论(0)
提交回复
热议问题