如何在使用ggplot绘图时抑制警告 [英] how to suppress warnings when plotting with ggplot

查看:110
本文介绍了如何在使用ggplot绘图时抑制警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将缺失的值传递给ggplot时,它非常友善,并警告我们它们存在。这在交互式会话中是可以接受的,但是在编写报告时,不要将输出混杂在警告中,特别是如果有很多警告。

  library(ggplot2)
library(reshape2)$ b下面的例子有一个标签丢失,会产生一个警告。 $ b mydf < - data.frame(
species = sample(c(A,B),100,replace = TRUE),
lvl = factor(sample(1:3, (mydf,table(species,lvl)))
名称(实验室)< -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对象时抑制警告?

解决方案

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)


When passing missing values to ggplot, it's very kind and warns us that they are present. This is acceptable in an interactive session, but when writing reports, you do not the output get cluttered with warnings, especially if there's many of them. Below example has one label missing, which produces a warning.

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)

If we wrap suppressWarnings around the last expression, we get a summary of how many warnings there were. For the sake of argument, let's say that this isn't acceptable (but is indeed very honest and correct). How to (completely) suppress warnings when printing a ggplot2 object?

解决方案

A more targeted plot-by-plot approach would be to add na.rm=TRUE to your plot calls. E.g.:

  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)

这篇关于如何在使用ggplot绘图时抑制警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆