Why does ggplot annotate throw this warning: In is.na(x) : is.na() applied to non-(list or vector) of type 'expression'
Asked Answered
B

2

7

I would like to annotate a ggplot plot with a simple equation. The code below does it but it throws a warning about applying is.na():

library(ggplot2)
ggplot() +
  annotate(geom = "text", x = 1, y = 1, 
           label = expression(paste(beta, pi, "(1-" , pi, ")")),
           hjust = "left")
Warning message:
In is.na(x) : is.na() applied to non-(list or vector) of type 'expression'

What is the proper syntax to include the expression without the warning?

Why does this not make the warning go away?

suppressWarnings(
  ggplot() +
    annotate(geom = "text", x = 1, y = 1, 
             label = expression(paste(beta, pi, "(1-" , pi, ")")),
             hjust = "left")
)

I am using R version 4.0.2 with ggplot2 version 3.3.2

Behr answered 26/7, 2020 at 0:47 Comment(0)
F
12

The annotate() function does not support expressions. you need to pass in a string and set parse=TRUE. You can do

  annotate(geom = "text", x = 1, y = 1, 
           label = 'paste(beta, pi, "(1-" , pi, ")")', parse=TRUE,
           hjust = "left")
Fung answered 26/7, 2020 at 1:59 Comment(1)
The linked thread is interesting, but it is 5 years old and back then it seemed to have failed. the code by the OP does result in a nicely parsed expression, but just with warning. I am therefore not so sure if it is true that "annotate does not support expression".Zenas
P
7

The way to run the code without warning, would be to pass the expression as a list and set parse = TRUE.

library(ggplot2)
ggplot() +
  annotate(geom = "text", x = 1, y = 1, 
           label = list('paste(beta, pi, "(1-" , pi, ")")'),
           hjust = "left", parse = TRUE)

Created on 2021-02-01 by the reprex package (v0.3.0)

The warning is generated by trying to evaluate is.na() on an expression.

is.na(expression(1 + 2))
#> Warning in is.na(expression(1 + 2)): is.na() applied to non-(list or vector) of
#> type 'expression'
#> [1] FALSE

In ggplot2, that sort of check happens in ggplot2:::is_complete(expression(1 + 2)), which is called in ggplot2:::detect_missing. I found out about this by setting options(warn = 2) and then using the traceback() to lead me to these functions.

Philistine answered 1/2, 2021 at 9:30 Comment(1)
thanks. That's the obscure function under the hood I was looking for :)Zenas

© 2022 - 2024 — McMap. All rights reserved.