简体   繁体   中英

Using ggmap. What the error “Computation failed in `stat_density2d()`: missing value where TRUE/FALSE needed” means?

I am using R as a GIS tool for creating maps. I wanted to create a contour, or heatmap of a species distribution on a geographical area. I wanted to see on the map where each species (animal or plant) is present and color the area in a specific color. I am using a dataset downloaded from GBIF.

You can download the datasets from my GitHub ([ https://github.com/RosarioIacono/stackoverflow_question/blob/master/species2t.csv][1] ).

species <- read.delim("./species.txt")
library(readr)
species2t <- read_csv("species2t.csv")
View(species2t)


ggmap(map1)+
    stat_density_2d(data = subset(species2t, order=="Anseriformes"),
aes( x = decimalLongitude,
     y = decimalLatitude,
     fill = ..level..),
                    alpha = .3,
                    geom = "polygon",
                    color = species)+
theme(legend.position = "none")

But I get an error:

Error: Aesthetics must be either length 1 or the same as the data (190): colour

I don't have your data frame, but I think your problem comes with one of the groups having n=1. This can be caused by, some of your species_dens's longitude and latitude being out of the map:

library("ggmap")
map <- c(left = -0.7, bottom = 53, right =-0.3 , top =53.6 )

map1<-get_stamenmap(map, maptype = "toner-lite")

#simulate data
species_dens = data.frame(species=c("A","B","A","B"),
decimalLongitude=c(-0.4,-0.5,-0.3,-0.2),
decimalLatitude=c(53.1,53.2,53.3,53.4))

# returns your error
ggmap(map1)+
geom_density_2d(data = species_dens,aes( x = decimalLongitude,
                                             y = decimalLatitude,
                                             colour = species))

From the above, you can see the last data point is off the map, so if you do geom_density with your limits, the species "B" will have n=1. Using your current dataset, if you set the colors to be species, you still end up with n=1:

library(readr)
species2t <- read_csv("species2t.csv")

X=subset(species2t, order=="Anseriformes")
table(X$species)

       Anas crecca Anas platyrhynchos      Anas strepera        Anser anser 
                 1                  1                  1                  1 
   Aythya fuligula        Cygnus olor    Tadorna tadorna 
                 1                  1                  1 

This means you cannot colour according to species. But you see how this order is distributed:

ggmap(map1)+
stat_density_2d(data = X,
aes( x = decimalLongitude,
     y = decimalLatitude,
     fill = ..level..),
     alpha = .3,
     geom = "polygon")+
theme(legend.position = "none")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM