ggplot2expressionannotate

How to resolve this waring: is.na() applied to non-(list or vector) of type 'expression'?


The following R code

library(ggplot2)
ggplot() + 
  annotate("text", x = 1, y = 1, label=expression(paste("model 1, ", italic(R)^2, ": 0.50")), 
    size = 14/.pt, col='blue', parse=TRUE)

throws a warning:

In is.na(x) : is.na() applied to non-(list or vector) of type 'expression'

I have trouble finding a solution for this.


Solution

  • I started looking into why this occurs, but it quickly got very complicated (e.g. https://github.com/tidyverse/ggplot2/pull/2867). There is an open issue with some more background info (https://github.com/tidyverse/ggplot2/issues/4644) but, basically, my understanding is that annotate() expects a character string, not an expression; if you convert the expression to a character string it doesn't throw the warning:

    library(ggplot2)
    # warning
    ggplot() + 
      annotate("text", x = 1, y = 1, label = expression(paste("model 1, ", italic(R)^2, ": 0.50")), 
               size = 14/.pt, col='blue', parse=TRUE)
    #> Warning in is.na(x): is.na() applied to non-(list or vector) of type
    #> 'expression'
    

    # no warning
    ggplot() + 
      annotate("text", x = 1, y = 1, label = as.character(expression(paste("model 1, ", italic(R)^2, ": 0.50"))), 
               size = 14/.pt, col='blue', parse=TRUE)
    

    # no warning
    ggplot() + 
      annotate("text", x = 1, y = 1, label = "model~1*','~italic(R)^2:~0.50", 
               size = 14/.pt, col='blue', parse=TRUE)
    

    Created on 2023-10-03 with reprex v2.0.2