问题
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\n 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:
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
回答1:
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\n per municipality", breaks =levels(study_area.map$brazil_loss_new2), labels=levels(study_area.map$brazil_loss_new2))+
theme()+
coord_fixed()
回答2:
Does including na.omit()
around the data call get you what you want?
ggplot(na.omit(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\n per municipality",
breaks = levels(study_area.map$brazil_loss_new2),
labels = levels(study_area.map$brazil_loss_new2)) +
theme() +
coord_fixed()
来源:https://stackoverflow.com/questions/54426144/how-to-remove-na-from-facet-wrap-in-ggplot2