【问题标题】:How to suppress warnings when plotting with ggplot使用ggplot绘图时如何抑制警告
【发布时间】:2012-11-08 09:52:41
【问题描述】:

当将缺失值传递给 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 对象时如何(完全)抑制警告?

【问题讨论】:

  • 既然你提到了报告:你可以在knitr中抑制警告输出。

标签: r ggplot2


【解决方案1】:

您需要在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() 可能更容易。

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() 调用产生的警告。

【讨论】:

  • 有趣的是,显式调用 print 是如何工作的,但当这是通过调用 ggplot 而不是将其分配给对象来隐式完成时则不然。
  • @RomanLuštrik 那是因为实际的调用类似于print(suppressWarnings(plt)) 你想要suppressWarnings(print(plt)) 还是我错过了你的意思?
  • 是的,你成功了。我没有认真考虑如何隐式调用 print。
【解决方案2】:

一种更有针对性的逐个情节方法是将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)

【讨论】:

  • +1 不错的答案。解决警告的根本原因并处理这些问题总是比抑制警告更好。
  • +1 同意@Andrie,尽管我确实发现收到有关缺失值的警告令人放心——它有助于我检查它是否在做正确的事情。当然不是说我不信任哈德利。
  • 仅供参考:对于stat_smooth,此技术不起作用。 (错误)
【解决方案3】:

在您的问题中,您提到了报告撰写,因此设置全局警告级别可能会更好:

options(warn=-1)

默认是:

options(warn=0)

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2018-07-11
    • 2019-02-25
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多