OpenStreet
Map with ggplot2
There are several ways to visualize spatial data in R, using common map engines like Google Maps or OpenStreetMap. Google Maps offers the functionality with the use of ggmap
package. However, two issues emerged, that made the use of Google Maps difficult. These are:
Google Maps API key is now required (it wasn’t, some time ago). Still you can obtain the key for free (for limited requests) but you need to reguster to Google Cloud Platform, create application, etc.
There are some compatibility isses with ggmap
package. There seem to be two versions aviabiable: CRAN version and github version (known as dkahle/ggmap
).
This documents intends to use OpenStreetMap to make spatial analyses as an alternative approach.
Threre are multiple documents and tutorials showing how to use OpenStreetMap
package with common graphics
package. However, ggplot2
offers much more functionality. In this document we focus on using ggplot
to plot on OpenStreetMap map fragment.
Prepare environment: clear workspace
rm(list=ls())
Key package needed is OpenStreetMap
. CRAN specification can be accessed here.
Package ggmap
is needed only to use crime
dataset.
library(OpenStreetMap)
library(ggplot2)
library(ggmap)
This example bases on crime
dataset. However, thefts
subdataset has been created as crime
contains many records, which can be difficult to visualize.
data("crime")
thefts <- subset(crime, offense == "auto theft")
Bottom left and top right points coorinates are specified.
p1.lat <- 29.7
p1.lon <- -95.5
p2.lat <- 30
p2.lon <- -95.1
OSM Comes with variety of types, e.g.: “osm”, “stamen-toner”, “stamen-terrain”. Notice that in order to plot Large OpenStreetMap
map, we cannot use standard ggplot
functions as it expects dataframe. In order to plot downloaded map, we use autoplot
function (it also comes from ggplot2
package).
map <- openmap(c(p1.lat,p1.lon),c(p2.lat,p2.lon), zoom = 11,
type = "stamen-terrain",
mergeTiles = TRUE)
autoplot(map)