Grabbing a background map
There are two steps to adding a map to a ggplot2
plot with ggmap
:
- Download a map using
get_map()
- Display the map using
ggmap()
As an example, let's grab a map for New York City:
library(ggmap)
nyc <- c(lon = -74.0059, lat = 40.7128)
nyc_map <- get_map(location = nyc, zoom = 10)
get_map()
has a number of arguments that control what kind of map to get, but for now you'll mostly stick with the defaults. The most important argument is the first, location
, where you can provide a longitude and latitude pair of coordinates where you want the map centered. (We found these for NYC from a quick google search of "coordinates nyc".) The next argument, zoom
, takes an integer between 3 and 21 and controls how far the mapped is zoomed in. In this exercise, you'll set a third argument, scale
, equal to 1
. This controls the resolution of the downloaded maps and you'll set it lower (the default is 2) to reduce how long it takes for the downloads.
Displaying the map is then as simple as calling ggmap()
with your downloaded map as the only argument: ggmap(nyc_map)
Your turn! We are going to be looking at house sales in Corvallis, but you probably have no idea where that is! Let's find out.
This is a part of the course
“Visualizing Geospatial Data in R”
Exercise instructions
We've created for you a pair of coordinates called corvallis
. Get a map centered on Corvallis at the following zoom levels and use ggmap()
to plot each. Don't forget to set scale = 1
to reduce download times.
zoom = 5
(Corvallis is in the State of Oregon on the West Coast of the USA.)zoom = 13
(The Willamette River runs through town, and Corvallis is the home of Oregon State University.)
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(ggmap)
corvallis <- c(lon = -123.2620, lat = 44.5646)
# Get map at zoom level 5: map_5
map_5 <- get_map(___, zoom = ___, scale = 1)
# Plot map at zoom level 5
ggmap(___)
# Get map at zoom level 13: corvallis_map
corvallis_map <- ___
# Plot map at zoom level 13