The ggmap package enables the visualization of spatial data and spatial statistics in a map format using the layered approach of ggplot2. This package also includes basemaps that give your visualizations context including Google Maps, Open Street Map, Stamen Maps, and CloudMade maps. In addition, utility functions are provided for accessing various Google services including Geocoding, Distance Matrix, and Directions.

The ggmap package is based on ggplot2, which means it will take a layered approach and will consist of the same five components found in ggplot2. These include a default dataset with aesthetic mappings where x is longitude, y is latitude, and the coordinate system is fixed to Mercator. Other components include one or more layers defined with a geometric object and statistical transformation, a scale for each aesthetic mapping, coordinate system, and facet specification. Because ggmap is built on ggplot2 it has access to the full range of ggplot2 functionality.

In this exercise you’ll learn how to use the ggmap package to plot various types of spatial visualizations.

Step 1: Creating a Basemap

There are two basic steps to create a map with ggmap. The details are more complex than these two steps might imply, but in general you just need to download the map raster and then plot operational data on the basemap. Step 1 is to download the map raster, also known as the basemap. This is accomplished using the get_map() function, which can be used to create a basemap from Google, Stamen, Open Street Map, or CloudMade. You’ll learn how to do that in this step. In a future step you’ll learn how to add and style operational data in various ways.

  1. First, load the libraries that we’ll need for this exercise
library(ggplot2)
library(ggmap)
library(readr)
library(dplyr)
  1. Create a variable called myLocation and set it to California. Call the get_map() function with a zoom level of 6, and plot the map using the ggmap() function, passing in a reference to the variable returned by the get_map() function. The default map type is Google Maps with a style of Terrain.
myLocation = 'California'
myMap = get_map(location = myLocation, zoom = 6)
ggmap(myMap)