I want to plot a map with a raster overlaying a GoogleMaps base map in ggplot2. Therefore, I used
bm <- ggmap(get_map(location = "Bangkok", maptype = "hybrid"))
bm + inset_raster(as.raster(r), xmin = r@extent, xmax = r@extent,
ymin = r@extent, ymax = r@extent)
After a while, I found a way to solve this problem. Converting the raster to polygons! This idea then basically was implemented after Marc Needham's blog entry.
Yet, there is one drawback: ggplot gets really slow with large numbers of polygons, which you will inevitably face. However, you can speed things up by plotting into a
png() (or other) device.
Here is a code example:
library(raster) library(ggplot2) library(ggmap) r <- raster(....) # any raster you want to plot rtp <- rasterToPolygons(r) rtp@data$id <- 1:nrow(rtp@data) # add id column for join rtpFort <- fortify(rtp, data = rtp@data) rtpFortMer <- merge(rtpFort, rtp@data, by.x = 'id', by.y = 'id') # join data bm <- ggmap(get_map(location = "Shanghai", maptype = "hybrid", zoom = 10)) bm + geom_polygon(data = rtpFortMer, aes(x = long, y = lat, group = group, fill = layer), alpha = 0.5, size = 0) + ## size = 0 to remove the polygon outlines scale_fill_gradientn(colours = topo.colors(255))
This results in something like this: