如何从 ggplot2 的 facet_wrap 中删除 NA?

问题描述 投票:0回答:3

我正在尝试使用 facet_wrap 在 ggplot2 中制作多边形地图。我的变量“作物”中有两个因子水平(大豆、玉米)但是,我得到了三个地块:大豆、玉米和一个具有 NA 值的地块。此外,前两个方面不显示 NA 值-

这是我制作地图的代码:

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

这就是我得到的:

如果我使用 na.omit 我会得到下图(更好,但前两个图中仍然缺少 NA 值)

enter image description here

包括每个变量和市政当局的行,无论感兴趣的变量是否为 NA,最终解决了问题。这就是我要找的东西:

Yield losses by municipalities with NA values

r ggplot2 na facet-wrap
3个回答
2
投票

您可以在调用 ggplot 函数时删除 NA。删除核心数据函数中的 NA。这样它就不会绘制它们

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

0
投票

在数据通话中包括

na.omit()
是否能让您得到想要的东西?

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

0
投票

我在运行以下代码时遇到了同样的问题,只需添加

na.omit()
对我有用:

ggplot(data = mma_male_df) +
  geom_bar(mapping = aes(x = cut(date, "12 months"), fill=method_new)) +
  facet_wrap(~division, ncol = 4, drop = T) +
  scale_x_discrete(labels = function(x) format(as.Date(x), "%Y")) +
  theme(axis.text.x = element_text(angle = 45)) +
  labs(title = "Men's MMA Fights by Year and Outcome", x = "Year", y = "Number of Fights", fill = "Fight Outcome")```

----------

ggplot(data = na.omit(mma_male_df)) +
  geom_bar(mapping = aes(x = cut(date, "12 months"), fill=method_new)) +
  facet_wrap(~division, ncol = 4, drop = T) +
  scale_x_discrete(labels = function(x) format(as.Date(x), "%Y")) +
  theme(axis.text.x = element_text(angle = 45)) +
  labs(title = "Men's MMA Fights by Year and Outcome", x = "Year", y = "Number of Fights", fill = "Fight Outcome")
© www.soinside.com 2019 - 2024. All rights reserved.