使用ggmap绘制物种分布热力图时两类报错的原因及解决咨询
嗨,我来帮你搞定这两个报错,让你顺利画出物种分布的等高线/热力图~
错误1:Computation failed in
stat_density2d(): missing value where TRUE/FALSE needed 这个报错的核心是stat_density2d在计算二维密度分布时卡壳了——你的筛选后数据里存在缺失的经度或纬度值(NA),而密度计算要求每一条数据都有完整的经纬度信息,只要有一个NA,程序就无法完成计算。
解决办法:
- 先确认缺失值的数量:
# 检查Anseriformes类数据的经纬度缺失情况 sum(is.na(subset(species2t, order=="Anseriformes")[,c("decimalLongitude","decimalLatitude")]))
- 清理缺失值,推荐用
dplyr的drop_na更直观:
library(dplyr) clean_data <- species2t %>% filter(order == "Anseriformes") %>% drop_na(decimalLongitude, decimalLatitude)
处理后的clean_data没有缺失的经纬度,再用来绘图就不会触发这个错误了。
错误2:Error: Aesthetics must be either length 1 or the same as the data (190): colour
这个报错是因为你在aes()里写了color = species,但species是你单独读取的外部对象,和当前stat_density2d用到的190行数据长度不匹配。而且这里你应该是想给等高线设置颜色,要么用固定色,要么用当前数据内的变量映射,不能用外部对象。
解决办法:
- 如果想给所有等高线设置统一颜色,把
color放在aes()外面,比如设成深灰色:
color = "darkgray"
- 如果你想按数据内的变量(比如具体物种名)区分颜色,要使用当前数据里的列,比如
color = speciesName(假设你的数据有这个列),但如果已经筛选了Anseriformes类,大部分数据属于同一类群,固定颜色会更合适。
修正后的完整代码示例
library(ggmap) library(readr) library(dplyr) # 读取数据 species2t <- read_csv("species2t.csv") # 清理目标物种的经纬度缺失值 clean_anseriformes <- species2t %>% filter(order == "Anseriformes") %>% drop_na(decimalLongitude, decimalLatitude) # 获取底图(如果还没准备map1) # 用数据的经纬度均值作为中心,调整zoom到合适大小 map_center <- c(lon = mean(clean_anseriformes$decimalLongitude), lat = mean(clean_anseriformes$decimalLatitude)) map1 <- get_map(location = map_center, zoom = 10) # 绘制等高线填充图 ggmap(map1) + stat_density_2d(data = clean_anseriformes, aes(x = decimalLongitude, y = decimalLatitude, fill = ..level..), alpha = .3, geom = "polygon", color = "darkgray") + theme(legend.position = "none")
如果想画热力图,也可以把geom = "polygon"换成geom = "raster",或者用geom_bin2d绘制网格型热力图,更贴合“热力”的视觉效果。
内容的提问来源于stack exchange,提问作者Rosario
相关产品推荐
相关产品推荐

