1

I am trying to plot a predicted surface (raster layer) over a ggmap object that contains base imagery from Google Earth. I have produced the map that I want however, I am struggling to add the legend scalebar.

To add the raster over top the ggmap object, I used the inset_raster function and I am not sure where to map the aesthetics to produce the proper legend based on the color scale I assigned the raster.

Below is an example of my code. Does anyone have advice on how to add the legend based on the inset_raster object?

rsfmap <- ggmap(get_googlemap(center = c(lon = x, lat = y), 
                              zoom = 9, 
                              maptype = "hybrid"),
                              extent = "device", darken = 0.05, legend='right')

rsfmap+
  geom_point(aes(x=coords.x1, y=coords.x2), size=1, alpha=0.75, data=mydata) +
  inset_raster(as.raster(ggras, col=(topo.colors(500, alpha=0.4))), xmin = 
               ggras@extent[1], xmax = ggras@extent[2],ymin = ggras@extent[3], 
               ymax =  ggras@extent[4], interpolate = TRUE)
0

Okay, I figured it out after finding this link: https://datacarpentry.org/r-raster-vector-geospatial/02-raster-plot/

Instead of using the inset_raster function. I transformed my raster into a dataframe and used the geom_raster function to add it to my ggmap, which has a more straight-forward mapping to the legend. Next, I used coord_fixed instead of coord_cartesian and set my ratio = 1.5 to improve the default appearance used with just coord_fixed. Really happy with the finished product. Hope someone finds this helpful!

` myras<- projectRaster(my_prediction, crs = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")) #convert to ggmap projection myras<- as.data.frame(myras, xy=T, na.rm=T)

rsfmap <- ggmap(get_googlemap(center = c(lon = x, lat = y), 
                              zoom = 9, 
                              maptype = "hybrid"),
                              extent = "device", darken = 0.05, legend='bottomleft')

rsfmap+
  geom_point(aes(x=coords.x1, y=coords.x2), size=2, alpha=1, shape=15, color='black', show.legend = T, data=mydata) +

  geom_raster(data = myras, aes(x = x, y = y, fill=layer)) +

  coord_fixed(ratio=1.5) +

  scale_fill_gradientn(colours=topo.colors(500, alpha=0.4), name="Nest\nProbability") +

  theme(legend.background=element_rect(fill=alpha('white', 0.4)),
        legend.text = element_text(size=12))`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.