R 如何在使用ggplot打印时抑制警告

R 如何在使用ggplot打印时抑制警告,r,ggplot2,R,Ggplot2,当将缺少的值传递给ggplot时,它非常友好,并警告我们它们存在。这在交互式会话中是可以接受的,但是在编写报告时,您不会让输出中出现杂乱无章的警告,特别是在警告很多的情况下。下面的示例缺少一个标签,这会产生警告 library(ggplot2) library(reshape2) mydf <- data.frame( species = sample(c("A", "B"), 100, replace = TRUE), lvl = fac

当将缺少的值传递给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)
库(ggplot2)
图书馆(E2)

mydf您需要围绕
print()
调用
suppressWarnings()
,而不是创建
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> 
将最终打印指定给对象然后
print()
可能更容易

无效,因为实际上您正在调用
print(suppressWarnings(plt))
,而

R> suppressWarnings(print(plt))
R>

确实有效,因为
suppressWarnings()
可以捕获由
print()
调用引起的警告。

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

options(warn=-1)
默认值为:

options(warn=0)

一种更有针对性的逐点绘图方法是将
na.rm=TRUE
添加到绘图调用中。 例如:


既然您提到了报告:您可以在knitr中抑制警告输出。+1回答得不错。解决警告的根本原因并处理这些问题总是比抑制警告要好得多。+1同意@Andrie的观点,尽管我确实觉得得到关于缺少值的警告会让人放心——这有助于我检查它是否做了正确的事情。当然,这并不是说我不信任哈德利。仅供参考:对于
stat\u smooth
来说,这种技术不起作用。(bug)有趣的是,显式调用
print
是如何工作的,但如果通过调用
ggplot
隐式地完成,而不是将其分配给一个对象,@RomanLuštrik这是因为实际的调用类似于
print(suppressWarnings(plt))
您想要的
suppressWarnings(print(plt))
还是我没有领会你的意思?是的,你说得对。我没有认真思考print是如何被隐式调用的。
options(warn=-1)
options(warn=0)
  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)