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