我有一个通用的plot_data(data)
方法。 有时传入的数据具有我用于填充的变量的所有 NA,这会导致错误
Error in seq.default(h[1], h[2], length.out = n) :
'to' must be a finite number
例如:
df <- data.frame(
x = c(1, 2, 3, 4),
y = c(10, 15, 20, 25),
foo = factor(c(NA, NA, NA, "yes"), levels=c("yes", "no"))
)
ggplot(df, aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity") # works
ggplot(df[1:3, ], aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity") # error
我不明白为什么情节不应该在案例 2 中呈现(只是所有灰色条(。 有没有简单的方法来克服这个问题?
您可以使用forcats
包中的fct_explicit_na
使缺失值成为显式因子水平。(请注意,基本包中的addNA
在这里不起作用;后者将 NA 添加为关卡,但不会导致它显示在绘图中。
ggplot(df[1:3, ],
aes(x=x, y=y, fill=forcats::fct_explicit_na(foo)))+
geom_bar(stat = "identity")
旁白:如果您确实有其他值并且只想为 NA 值使用不同的默认颜色,则可以更改该选项scale_fill_discrete(na.value = "some colour other than grey")
有点恶心...
ggplot(df[1:3,], aes(x=x, y=y, if(!all(is.na(foo))){fill=foo})) +
geom_bar(stat = "identity")
灰色表示没有填充。例如,下面的将给出灰色绘图:
ggplot(df, aes(x=x, y=y))+geom_bar(stat = "identity")
在您的示例中,当包含foo = "yes"
的行时,带有foo = NA
的行实际上没有填充颜色,只填充了最后一行。但是,当排除最后一行时,列中的所有值foo
变为NA
。正如错误所暗示的那样,填充映射中to
的结尾必须是有限数,而不是NA
。规避此问题的一种方法是将NA
转换为字符串,例如:
ggplot(df[1:3, ], aes(x=x, y=y, fill=ifelse(is.na(foo), "NA", foo)))+geom_bar(stat = "identity")