Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

r - Eliminating NAs from a ggplot

Very basic question here as I'm just starting to use R, but I'm trying to create a bar plot of factor counts in ggplot2 and when plotting, get 14 little colored blips representing my actual levels and then a massive grey bar at the end representing the 5000-ish NAs in the sample (it's survey data from a question that only applies to about 5% of the sample). I've tried the following code to no avail:

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

The addition of the na.rm argument here has no apparent effect.

meanwhile

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

gives me

"Error: Aesthetics must either be length one, or the same length as the data"

as does affixing the na.omit() to the_variable, or both MyData and the_variable.

All I want to do is eliminate the giant NA bar from my graph, can someone please help me do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the function subset inside ggplot2. Try this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...