Skip to content

Instantly share code, notes, and snippets.

@benfasoli
Last active January 25, 2018 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfasoli/eff732a8870998e43727f6ade5405274 to your computer and use it in GitHub Desktop.
Save benfasoli/eff732a8870998e43727f6ade5405274 to your computer and use it in GitHub Desktop.
Overlay partial transparency gridded raster to grayscale Google Map terrain layer
library(ggmap)
library(tidyverse)
# Fetch SLC-centric grayscale Google Map terrain layer
basemap <- get_googlemap(center = c(lon = -112.0, lat = 40.6), zoom = 10,
scale = 2, maptype = 'terrain', color = 'bw')
# Display downloaded map
ggmap(basemap)
# Create gridded example data
xyz <- expand.grid(x = seq(-112.4, -111.6, length.out = 100),
y = seq(40.3, 40.9, length.out = 100))
xyz$z <- with(xyz, abs(x * y))
# Define color palette for raster plotting
cp <- c('blue','cyan','white','yellow','orange','red')
# Convert baselayer to cartesian coordinates (Google Maps uses Mercator) and
# overlay color filled raster with partial opacity
ggmap(basemap) +
coord_cartesian() +
geom_raster(data = xyz, aes(x = x, y = y, fill = z), alpha = 0.7) +
scale_fill_gradientn(colors = cp) +
labs(x = NULL, y = NULL, fill = NULL) +
theme(plot.margin = margin(0, 0, 0, 0, 'cm'))
ggsave('output-map-example.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment