如何与ggplot打印时禁止警告(how to suppress warnings when plo

2019-07-03 16:40发布

当通过缺失值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)

如果我们换suppressWarnings周围的最后一个表达式,我们得到了多少的警告有一个总结。 为了讨论的方便,让我们说,这是不能接受的(但确实是非常诚实和正确的)。 如何打印GGPLOT2对象时(完全)抑制警告?

Answer 1:

更有针对性的情节按剧情的方法是添加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)


Answer 2:

你需要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> 

它可能会更容易分配的最终情节的对象,然后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> 

究其原因,行为是当该地块实际绘制,而不是在创建表示剧情对象的警告才会产生。 交互使用过程中R将自动打印,所以虽然

R> suppressWarnings(plt)
Warning message:
Removed 1 rows containing missing values (geom_text).

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

R> suppressWarnings(print(plt))
R>

没有工作,因为suppressWarnings()可以捕获从产生的警告print()调用。



Answer 3:

在你的问题,你提到的报告撰写,所以它可能是更好的设置全局警告级别:

options(warn=-1)

默认为:

options(warn=0)


文章来源: how to suppress warnings when plotting with ggplot
标签: r ggplot2