【问题标题】:ggplot issue when using facets, geom_vline, with NAs使用带有 NA 的 facets、geom_vline 时的 ggplot 问题
【发布时间】:2016-03-23 15:35:22
【问题描述】:

当我运行下面的代码时,我在下面得到了进一步的错误。

library(ggplot2)
d = data.frame(id=rep(c(1,2),each=3),x=c(1:3,1:3),y=2:7,z=as.numeric(rep(NA,6)))
g = ggplot(d,aes(x,y))
g = g + geom_point() + geom_line()
g = g + geom_vline(aes(xintercept=z))
g = g + facet_wrap(~id)
print(g)

错误:

Error in FUN(X[[i]], ...) : subscript out of bounds
In addition: Warning message:
Removed 6 rows containing missing values (geom_vline). 

我知道上面的代码有点傻,但它应该可以工作。在实践中,通常我对 z 中的某些数字有数值,而对其他数字有 NA,但是当我获取数据的子集时,有时我有所有 NA,这会导致上述错误。当我使用旧版本的 ggplot2 时,我没有遇到这个问题。

这可以解决吗?

【问题讨论】:

  • 无法使用 R 版本 3.2.3 和 ggplot2 2.1.0 重现
  • 您可能想发布您正在使用的ggplot2 的版本。
  • 谢谢。我使用的是 ggplot2 2.0.0。我已经更新到 ggplot2 2.1.0 并且它解决了问题(对我来说需要 R 3.2.4)并且它可以工作

标签: r ggplot2


【解决方案1】:

问题出在你的线路上:

g = g + geom_vline(aes(xintercept=z))

因为 z 在每种情况下都是 NA,所以这会产生错误。如果至少有一个值是实数,则不会出现此错误。删除它,其余的都可以正常工作。

正如您在问题中所说,无论值是否全部为 NA,您都希望代码始终有效。您可以通过替换来实现:

g = g + geom_vline(aes(xintercept=z))

使用 if 语句:

if (!all(is.na(z))) g <- g + geom_vline(aes(xintercept=z))

现在,如果您的 z 列全部为 NA,代码将忽略 geom_vline 调用。

z <- c(NA, NA, NA, NA, NA, NA)
d = data.frame(id=rep(c(1,2),each=3),x=c(1:3,1:3),y=2:7,z=as.numeric(z))
g = ggplot(d,aes(x,y))
if (!all(is.na(z))) g <- g + geom_vline(aes(xintercept=z))
g = g + geom_point() + geom_line()
g = g + facet_wrap(~id)
print(g)

【讨论】:

    【解决方案2】:

    更新到 ggplot2 2.1.0(和 R 3.2.4)解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2021-08-30
      • 2020-02-05
      • 2019-08-04
      相关资源
      最近更新 更多