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

JT8*_*T85 15 r ggplot2

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

 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~.)
Run Code Online (Sandbox Code Playgroud)

当添加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
Run Code Online (Sandbox Code Playgroud)

可能它在scales不自由时使用所有方面的最小值和最大值.何时scales是空闲的,它不知道只包含缺失的方面要采用哪个值?

有解决方法吗?

Jaa*_*aap 3

我查看了两种解决方案。

1)

ggplot(data = d, aes(x, y)) + 
  geom_point() +
  facet_grid(z~.,scales="free_x")
Run Code Online (Sandbox Code Playgroud)

确实有效,但给出的结果与没有该部件时相同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)
Run Code Online (Sandbox Code Playgroud)

这是行不通的。当单独绘制图时,您会发现p5无法绘制。这是因为 forz=5 y仅有 NA。

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

free_x这就是它起作用的原因(尽管它给出了相同的结果)。

结论:当你的一组只有 NA 时,你不能scales="free"在你的绘图中使用。因此,你有两个选择(在我看来):

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