【问题标题】:ggplot2 error when fill values are all NA: Error in seq.default(h[1], h[2], length.out = n) :填充值全部为 NA 时出现 ggplot2 错误: seq.default(h[1], h[2], length.out = n) 中的错误:
【发布时间】:2017-08-25 11:35:34
【问题描述】:

我有一个通用的plot_data(data) 方法。有时传入的数据包含我用于 fill 的变量的所有 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 中呈现(只是所有灰色条)。有没有简单的方法可以解决这个问题?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用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") 中的选项

    【讨论】:

      【解决方案2】:

      有点恶心……

      ggplot(df[1:3,], aes(x=x, y=y, if(!all(is.na(foo))){fill=foo})) +
        geom_bar(stat = "identity")
      

      【讨论】:

        【解决方案3】:

        灰色表示没有填充。例如下面的会给出一个灰色的绘图:

        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")

        【讨论】:

          猜你喜欢
          • 2020-05-05
          • 1970-01-01
          • 2021-08-11
          • 1970-01-01
          • 1970-01-01
          • 2021-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多