消除ggplot中的NA

Ben*_*ler 23 r ggplot2

这是非常基本的问题,因为我刚刚开始使用R,但我正在尝试在ggplot2中创建因子计数的条形图,并且当绘图时,得到14个小颜色的blips代表我的实际水平,然后是一个巨大的灰色条形图.结束表示样本中的5000-na NAs(它的调查数据来自仅适用于约5%样本的问题).我尝试了以下代码无济于事:

ggplot(data = MyData,aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
   geom_bar(stat="bin") 
Run Code Online (Sandbox Code Playgroud)

在这里添加na.rm参数没有明显的效果.

与此同时

ggplot(data = na.omit(MyData),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
   geom_bar(stat="bin") 
Run Code Online (Sandbox Code Playgroud)

给我

"错误:美学必须是长度一,或与数据长度相同"

na.omit()the_variable,或者MyData和the_variable一样.

我想做的就是从我的图表中消除巨大的NA栏,有人可以帮我这么做吗?

raf*_*ira 29

你可以使用subset里面的功能ggplot2.试试这个

library(ggplot2)

data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example

ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) + 
geom_bar(stat="bin")
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,`iris` 没有 NA。) (3认同)
  • 现在确实如此.谢谢你的抬头:) (2认同)
  • 哈!这是处理评论的好方法))我想,对于几乎任何情况,都有一个非常适合的数据集[来自 R 内置数据集](https://vincentarelbundock.github.io/Rdatasets/datasets.html) (2认同)

小智 13

此外,将 na.rm= TRUE 添加到您的 geom_bar() 将起作用。

ggplot(data = MyData,aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
   geom_bar(stat="bin", na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)

我在时间序列的循环中遇到了这个问题,并修复了它。缺失的数据将被删除,否则结果不会受到影响。


Jay*_*Kao 10

不知道你是否已经解决了问题。对于这个问题,您可以使用 dplyr 包中的“过滤器”功能。这个想法是过滤你感兴趣的变量的值不是NA的观察/行。接下来,您使用这些过滤后的观察值制作图表。您可以在下面找到我的代码,并注意数据框和变量的所有名称都是从您的问题提示中复制的。另外,我假设您知道管道操作员。

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 
Run Code Online (Sandbox Code Playgroud)

您应该能够删除情节上烦人的 NA。希望这有效:)


ika*_*sky 9

只是对@ rafa.pereira答案的更新.由于ggplot2是一部分tidyverse,使用方便的tidyverse函数来摆脱NA是有意义的.

library(tidyverse)
airquality %>% 
        drop_na(Ozone) %>%
        ggplot(aes(x = Ozone))+
        geom_bar(stat="bin")
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以使用drop_na()不带列规范; 然后将删除任何列中具有NA的所有行.


Bry*_*n F 8

尝试remove_missing使用vars = the_variable. 设置vars参数非常重要,否则remove_missing将删除任何列中包含 a 的所有行NA设置na.rm = TRUE将抑制警告消息。

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 
Run Code Online (Sandbox Code Playgroud)