简体   繁体   English

为什么 ggplot annotate 会抛出此警告:在 is.na(x): is.na() 应用于“表达式”类型的非(列表或向量)

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

I would like to annotate a ggplot plot with a simple equation.我想用一个简单的方程注释 ggplot plot 。 The code below does it but it throws a warning about applying is.na():下面的代码会执行此操作,但会引发有关应用 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?为什么这不会使警告 go 消失?

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我正在使用 R 版本 4.0.2 和 ggplot2 版本 3.3.2

The annotate() function does not support expressions . annotate() function 不支持表达式 you need to pass in a string and set parse=TRUE .您需要传入一个字符串并设置parse=TRUE You can do你可以做

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

The way to run the code without warning, would be to pass the expression as a list and set parse = TRUE .在没有警告的情况下运行代码的方法是将表达式作为列表传递并设置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)reprex package (v0.3.0) 于 2021 年 2 月 1 日创建

The warning is generated by trying to evaluate is.na() on an expression.警告是通过尝试对表达式求值is.na()生成的。

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 .在 ggplot2 中,这种检查发生在ggplot2:::is_complete(expression(1 + 2))中,在ggplot2:::detect_missing中调用: I found out about this by setting options(warn = 2) and then using the traceback() to lead me to these functions.我通过设置options(warn = 2)发现了这一点,然后使用traceback()引导我使用这些功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM