Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to remove NA from facet_wrap in ggplot2?

I am trying to use facet_wrap to make a polygon map in ggplot2. I have two factor levels (soybean, Maize) in my variable "crop" However, I am getting three plots: soybean, maize and one with NA values. In addition NA values are not displayed in the first two facets-

here is my code to make the map:

ggplot(study_area.map, aes(x=long, y=lat, group=group)) + 
  geom_polygon(aes(fill=brazil_loss_new2)) + 
  geom_path(colour="black") + 
  facet_wrap(~crop, ncol=2, drop=T) + 
  scale_fill_brewer(na.value="grey", palette="Blues", 
    name="Average production lossess
 per municipality", 
    breaks = levels(study_area.map$brazil_loss_new2), 
    labels = levels(study_area.map$brazil_loss_new2)) + 
  theme() + 
  coord_fixed()

and this is what I get:

enter image description here

If I use na.omit I get the following figure (which is better, but there are still the NA values missing in the first two plots)

enter image description here

Including rows for each variable and municipality no matter if the variable of interest is NA or not, finally solves the problem. Here is what I was looking for:

Yield losses by municipalities with NA values

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can remove the NA's in place while calling the ggplot function. Remove the NA's in the core data function. That way it wont plot them

ggplot(data = study_area.map[!(is.na(study_area.map[$brazil_loss_new2)),], aes(x=long, y=lat, group=group))+ 
geom_polygon(aes(fill=brazil_loss_new2))+ 
geom_path(colour="black")+ facet_wrap(~crop, ncol=2, drop=T)+ scale_fill_brewer(na.value="grey", palette="Blues", name="Average production lossess
 per municipality", breaks =levels(study_area.map$brazil_loss_new2), labels=levels(study_area.map$brazil_loss_new2))+ 
theme()+ 
coord_fixed()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...