ggplot2 关于我无法使用 `na.rm=T` 禁用的缺失的警告

ggplot2 warning about missings that I can't disable with `na.rm=T`

当您使用 ggplot2 绘图时,如果它自动删除缺失项,它会警告您。
我希望能够禁用该特定警告或将 na.rm 的默认值设置为 true 系统范围,但这不可能 AFAIK。

我知道我可以通过为我使用的每个 geom 指定 na.rm=T 来禁用它。但是当 ggplot 生成我没有明确指定的其他几何时,这会失败。在下面的示例中,我将使用我的原始数据在每个图上收到三个警告(当我分面时有 10 个,因此您可以在 knitr 报告中看到这变得很烦人)。 我可以用 na.rm=T 抑制两个警告,但我不能用 geom_segment 抑制第三个警告。顺带一提,mtcars也会出现这种情况,所以我就拿它来举例。

Warning message: Removed 23 rows containing missing values (geom_segment).

ggplot(data=mtcars, aes(x = disp, y = wt)) + 
    geom_linerange(stat = "summary", fun.data = "median_hilow", colour = "#aec05d", na.rm=T) + 
    geom_pointrange(stat = "summary", fun.data = "mean_cl_boot", colour = "#6c92b2", na.rm=T)

在我弄清楚之前,我可以使用 warning=FALSE 来处理有问题的块,但我不太喜欢那样,因为它可能会抑制我关心的警告。我也可以在数据集上使用 na.omit,但要确定我将在图中使用哪些变量需要大量工作和语法。

我想避免这种情况的唯一方法是不使用 stat_summary,而是自己计算摘要统计信息。对于你的例子,这没问题,但我承认这不是一个非常令人满意的解决方案。

# load dplyr package used to calculate summary
require(dplyr)
# calculate summary statistics
df <- mtcars %>% group_by(disp) %>% do(mean_cl_boot(.$wt))
# use geom_point and geom_segment with na.rm=TRUE
ggplot(data=mtcars, aes(x = disp, y = wt)) + 
  geom_linerange(stat = "summary", fun.data = "median_hilow", colour = "#aec05d") + 
  geom_point(data = df, aes(x = disp, y = y), colour = "#6c92b2") +
  geom_segment(data = df, aes(x = disp, xend = disp, y = ymin, yend = ymax), colour = "#6c92b2", na.rm=TRUE) 

或者,您可以编写自己的 mean_cl_boot 版本。如果 yminymaxNA,只需将它们设置为 y 的值。

# your summary function 
my_mean_cl_boot <- function(x, ...){
  res <- mean_cl_boot(x, ...)
  res[is.na(res$ymin), "ymin"] <- res[is.na(res$ymin), "y"]
  res[is.na(res$ymax), "ymax"] <- res[is.na(res$ymax), "y"]
  na.omit(res)
}
# plotting command
ggplot(data=mtcars, aes(x = disp, y = wt)) + 
  geom_linerange(stat = "summary", fun.data = "median_hilow", colour = "#aec05d", na.rm=T) + 
  geom_pointrange(stat = "summary", fun.data = "my_mean_cl_boot", colour = "#6c92b2", na.rm=T)