如何使用ggplot绘制时抑制警告

Rom*_*rik 47 r ggplot2

将缺失值传递给ggplot时,它非常友好并警告我们它们存在.这在交互式会话中是可以接受的,但是在编写报表时,输出不会出现警告,特别是如果有很多警告.下面的示例缺少一个标签,产生警告.

library(ggplot2)
library(reshape2)
mydf <- data.frame(
  species = sample(c("A", "B"), 100, replace = TRUE), 
  lvl = factor(sample(1:3, 100, replace = TRUE))
)
labs <- melt(with(mydf, table(species, lvl)))
names(labs) <- c("species", "lvl", "value")
labs[3, "value"] <- NA
ggplot(mydf, aes(x = species)) + 
   stat_bin() + 
   geom_text(data = labs, aes(x = species, y = value, label = value, vjust = -0.5)) +
   facet_wrap(~ lvl)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我们suppressWarnings绕过最后一个表达式,我们会得到有多少警告的摘要.为了论证,让我们说这是不可接受的(但确实非常诚实和正确).打印ggplot2对象时如何(完全)抑制警告?

Rei*_*son 47

你需要suppressWarnings()围绕print()调用,而不是创建ggplot()对象:

R> suppressWarnings(print(
+ ggplot(mydf, aes(x = species)) + 
+    stat_bin() + 
+    geom_text(data = labs, aes(x = species, y = value, 
+                               label = value, vjust = -0.5)) +
+    facet_wrap(~ lvl)))
R> 
Run Code Online (Sandbox Code Playgroud)

将最终绘图分配给对象可能更容易print().

plt <- ggplot(mydf, aes(x = species)) + 
   stat_bin() + 
   geom_text(data = labs, aes(x = species, y = value,
                              label = value, vjust = -0.5)) +
   facet_wrap(~ lvl)


R> suppressWarnings(print(plt))
R> 
Run Code Online (Sandbox Code Playgroud)

行为的原因是警告仅在实际绘制绘图时生成,而不是在创建表示绘图的对象时生成.R将在交互式使用期间自动打印,因此同时

R> suppressWarnings(plt)
Warning message:
Removed 1 rows containing missing values (geom_text).
Run Code Online (Sandbox Code Playgroud)

不起作用,因为,实际上,你在呼唤print(suppressWarnings(plt)),而

R> suppressWarnings(print(plt))
R>
Run Code Online (Sandbox Code Playgroud)

确实有效,因为它suppressWarnings()可以捕获print()呼叫产生的警告.


met*_*oia 44

一个更有针对性的逐个绘图方法是添加na.rm=TRUE到你的情节调用.例如:

  ggplot(mydf, aes(x = species)) + 
      stat_bin() + 
      geom_text(data = labs, aes(x = species, y = value, 
                                 label = value, vjust = -0.5), na.rm=TRUE) +
      facet_wrap(~ lvl)
Run Code Online (Sandbox Code Playgroud)

  • +1很好的答案.总是更好地解决警告的根本原因并处理这些问题,而不是抑制警告. (2认同)
  • 仅供参考:对于“stat_smooth”,此技术不起作用。(漏洞) (2认同)

csg*_*pie 22

在您的问题中,您提到报告编写,因此最好设置全局警告级别:

options(warn=-1)
Run Code Online (Sandbox Code Playgroud)

默认为:

options(warn=0)
Run Code Online (Sandbox Code Playgroud)