Search code examples
rggmapcran

stat_contour cannot be displayed in a ggmap


I am using a spatial heatmap to determine the geographic distribution of a species along the coast. To help, I used this page to create a spatial heatmap: Generating spatial heat map via ggmap in R based on a value. More especially I am looking at the second answer (bellow are my data)

Here is my script:

library(ggmap)
min.longitude <- 2.79
max.longitude <- 3.42
min.latitude <- 42.21
max.latitude <- 42.58

map <- get_map(c(left = min.longitude, 
                 bottom = min.latitude, 
                 right = max.longitude, 
                 top = max.latitude))

ggmap(map, extent = "device") +
  stat_contour(data = dat, aes(x = Long_X, y = Lat_Y, z = Mbiomass, 
                                   fill = ..level.., alpha = ..level..), geom = 'polygon') +
  scale_fill_gradient(name = "Biomass", low = "green", high = "red") +
  guides(alpha = "none")

The map is correctly displayed but I got the following message:

Warning messages:
1: stat_contour(): Zero contours were generated 
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

I really cannot understand why R cannot generate stat-contour while it can show points :

ggmap(map, extent = "device") +
  geom_point(data = dat, alpha = 0.5,
             aes(x = Long_X, y = Lat_Y, size = Mbiomass))

Any idea ?

Thanks in advance

my data:

> dat
    Mbiomass   Long_X    Lat_Y
1   1386.599 3.066622 42.53664
2   1131.857 3.082673 42.53298
3  19339.867 3.173415 42.44214
4   5841.449 3.169005 42.42566
5   5157.713 3.164887 42.40216
6   4021.591 3.163267 42.39184
7   8115.215 3.168353 42.38908
8   9463.714 3.103336 42.52609
9   4933.293 3.108787 42.52607
10  7076.145 3.123969 42.52196
11  8081.861 3.136561 42.51739
12  8605.169 3.137986 42.51420
13  2120.396 3.133304 42.50119
14 33706.221 3.153747 42.47877
15 25785.218 3.158125 42.47596
16 17201.229 3.158815 42.46965
17 15584.315 3.160875 42.46744
18 35637.482 3.164094 42.46573
19 18298.088 3.162248 42.46323
20 11903.925 3.160378 42.46119
21  8259.775 3.163468 42.45908
22 18076.537 3.167480 42.45759
23 15340.329 3.170177 42.44819

Solution

  • It's not clear to me what you are trying to do here. stat_contour will turn a regular grid of x, y, z values into a contour map. However, your data are all points along the coast. If you think a contour map makes sense here, then your two options are to fit a regular grid of points using interpolation or to try a weighted density plot, like this:

    ggmap(map, extent = "device") +
      geom_density2d_filled(data = tidyr::uncount(dat, weights = round(Mbiomass)), 
                 aes(x = Long_X, y = Lat_Y, alpha = stat(level)), fill = 'red',
                 h = 0.1) +
      guides(alpha = "none") +
      scale_alpha_manual(values = seq(0, 1, length.out = 14))
    

    Created on 2022-10-13 with reprex v2.0.2