R语言ggplot的geom_sf调用facet_wrap时多边形不全及出现NA分面问题
问题原因
- 最初代码使用
na.omit过滤了所有含缺失值的行,每个nome_popular(物种俗名)分组仅保留了有爬行动物记录的区域,因此分面中其余区域的多边形被省略。 - 修改后新增了全区域底图,但合并后的数据集中存在
nome_popular为NA的无效行,facet_wrap会为这些无效行单独生成NA分面。
解决方案
通过补全所有物种和区域的对应关系,确保每个物种分面都包含全部7个区域,同时过滤无效的NA数据即可解决问题,完整代码如下:
library(tidyverse) library(sf) library(readxl) # 读取爬行动物数据 serpentes <- read_excel("E:/22-serpentes_cg/R/serpentes_cg_finall.xlsx") # 统计各区域对应物种的记录总数 total_especies <- serpentes %>% rename(regiao_cg = REGIAO_CG) %>% group_by(especie, nome_popular, regiao_cg) %>% summarise(Total_esp = sum(quant), .groups = "drop") # 读取区域shapefile regiao <- sf::st_read("E:/22-serpentes_cg/geo/regioes_urbanas.shp") %>% rename(regiao_cg = REGIAO_CG) # 补全所有物种与区域的组合,无记录的物种-区域组合默认填充数量为0 total_especies_complete <- total_especies %>% complete(nome_popular, regiao_cg, fill = list(Total_esp = 0)) # 关联空间数据与物种统计数据 total_especies_shp <- dplyr::left_join(regiao, total_especies_complete, by = "regiao_cg") # 绘制分面地图 p_total_especies_shp <- ggplot(total_especies_shp %>% filter(!is.na(nome_popular))) + # 绘制全区域灰色底图 geom_sf(data = regiao, fill = "grey90", color = "white") + # 绘制对应物种的区域数量填充 geom_sf(aes(fill = factor(Total_esp)), color = "white") + scale_fill_brewer( palette = "Spectral", na.value = "grey", direction = -1, name = "Total de\nSepertens Regatadas" ) + facet_wrap(~nome_popular) p_total_especies_shp
核心修改说明
complete函数会生成所有nome_popular和regiao_cg的组合,确保每个物种对应的分组都包含全部7个区域,无记录的区域会自动填充为设定的默认值- 绘图前过滤
nome_popular不为NA的行,直接移除多余的NA分面 - 新增全区域浅灰色底图,与有记录区域的着色形成清晰区分,视觉效果更统一
内容的提问来源于stack exchange,提问作者wesleysc352
相关产品推荐
相关产品推荐

