繁体   English   中英

facet_grid和scales =“free”的行为,缺少数据

[英]Behaviour of facet_grid and scales=“free” with missing data

有人可以解释为什么这有效:

 d <- data.frame(x = 1:10, y = as.numeric(c(1:4,rep(NA,6))),z=rep(1:5,2))
 ggplot(data = d, aes(x, y)) + geom_point() +facet_grid(z~.)

scales="free"添加到facet_grid会抛出错误:

 d <- data.frame(x = 1:10, y = as.numeric(c(1:4,rep(NA,6))),z=rep(1:5,2))
 ggplot(data = d, aes(x, y)) + geom_point() +facet_grid(z~.,scales="free")

# Error in seq.default(from = best$lmin, to = best$lmax, by = best$lstep) : 
#  'from' must be of length 1

scales不自由时,它可能会使用所有刻面的最小值和最大值。 scales是免费的时,它不知道对仅包含缺失的方面采取哪个值?

有解决方法吗?

我看了两个解决方案。

1)

ggplot(data = d, aes(x, y)) + 
  geom_point() +
  facet_grid(z~.,scales="free_x")

有效,但给出与没有scales="free"部分相同的结果。

2)

library(gridExtra)
p1 <- ggplot(data = d[d$z==1,], aes(x, y)) + geom_point()
p2 <- ggplot(data = d[d$z==2,], aes(x, y)) + geom_point()
p3 <- ggplot(data = d[d$z==3,], aes(x, y)) + geom_point()
p4 <- ggplot(data = d[d$z==4,], aes(x, y)) + geom_point()
p5 <- ggplot(data = d[d$z==5,], aes(x, y)) + geom_point()
grid.arrange(p1,p2,p3,p4,p5,ncol=1)

这不起作用。 单独绘制图表时,您会发现p5无法绘制。 这是因为z=5 y只有NA。

当只有NA时尝试使用自由比例是不合逻辑的。 在我看来,这是一个概念性问题 这样做的原因是,如果不使用scales="free"参数,则使用其他子图的比例。 当使用scales="free"参数(或free_xfree_y )时,每个子图的比例将根据比例的长度设置。 当只有NA时,无法确定比例的长度,从而导致错误信息。

这就是为什么free_x可以工作的原因(虽然它给出了相同的结果)。

总结:当你的一个组只有NA时,你不能在你的情节中使用scales="free" 因此,您有两种选择(在我看来):

  • 省略scales="free"参数以获得所需的空子图。
  • 将NA替换为0 ,但这只是没有负值时的解决方案。

你也可以使用na.omit(数据帧)。 这对我有用。 我在722K行数据中只有一个(!)NA。 这足以得到这个错误。

我们可以解决这个问题,而来源是我们使用的是Capital X而不是公式中的小x,错误的是:ggplot(isotidy,aes(X = site,y = dN_fish,fill = site))+ geom_boxplot()并且应该如下所示:ggplot(isotidy,aes(x = site,y = dN_fish,fill = site))+ geom_boxplot()

我希望这有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM