2012-11-08 29 views
37

将缺失值传递给ggplot时,它非常友好,并警告我们它们存在。这在交互式会话中是可以接受的,但是在编写报告时,不要将输出混杂在警告中,特别是如果有很多警告。下面的示例中缺少一个标签,这会产生警告。如何在使用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) 

enter image description here

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

+2

既然你提到的报告:您可以抑制knitr警告输出。 –

+0

谢谢@DieterMenne我也会探讨这个选项。你怎么知道我是一个针织迷? :) –

回答

30

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

+1好的答案。解决警告的根本原因并处理这些问题总是会更好,而不是压制警告。 – Andrie

+0

+1同意@Andrie,虽然我确实发现可以获得关于缺失值的警告令人放心 - 它可以帮助我检查它是否正确。当然,我不相信哈德利。 –

+0

所有不错的选择,但这一个拿奖。 –

38

您需要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()

+0

有趣的是如何明确调用'print'工作,但不是当通过调用'ggplot'隐式完成而不是将其分配给一个对象时。 –

+1

@RomanLuštrik那是因为实际的调用就像'print(suppressWarnings(plt))''你想要'suppressWarnings(print(plt))''或者我想念你的意思? –

+0

是的,你已经钉了它。我对印刷如何隐含地被称为不够认真。 –

21

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

options(warn=-1) 

默认为:

options(warn=0)