[R-sig-Geo] overlay ggplot contour to base ggmap

massimo bressan m@@@|mo@bre@@@n @end|ng |rom @rp@@veneto@|t
Mon Apr 5 20:39:00 CEST 2021


please consider the following reproducible example

# set the origin of the grid
# in cartesian coordinates (epsg 32632)
xmin<-742966
ymin<-5037923

# set x and y axis
x<-seq(xmin, xmin+25*39, by=25)
y<-seq(ymin, ymin+25*39, by =25)

# define a 40 x 40 grid
mygrid<-expand.grid(x = x, y = y)

# set the z value to be interpolated by the contour
set.seed(123)
mygrid$z<- rnorm(nrow(mygrid))

library(tidyverse)

# plot of contour is fine
ggplot(data=mygrid, aes(x=x,y=y,z=z))+
  geom_contour()

library(ggspatial)

# transform coordinates to wgs84 4326
# (one of the many possible other ways to do it)
mygrid_4326<-xy_transform(mygrid$x, mygrid$y, from = 32632, to = 4326)

# create new grid with lon and lat
# (geographical coordinates espg 4326)
mygrid_4326<-mygrid_4326%>%
  mutate(z=mygrid$z)

# define the bounding box
my_bb<-c(min(mygrid_4326$x), min(mygrid_4326$y),
         max(mygrid_4326$x), max(mygrid_4326$y))
names(my_bb)<-c('left', 'bottom', 'right', 'top')

library(ggmap)

# get the background map (by a free provider)
mymap<-get_stamenmap(bbox = c(left = my_bb[['left']],
                              bottom = my_bb[['bottom']],
                              right = my_bb[['right']],
                              top = my_bb[['top']]),
                     zoom = 15,
                     maptype = 'toner-lite')

# the plot of the map is fine
mymap%>%
  ggmap()

# the overlay of the contour is failing
mymap%>%
  ggmap()+
  geom_contour(data=mygrid_4326, mapping=aes(x = x, y = y, z = z))
  #stat_contour(data=mygrid_4326, mapping=aes(x = x, y = y, z = z))

#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

now the problem is the overlay of the contour made with ggplot to the base
map made with ggmap

any help fo that?

thanks

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list