Get startedGet started for free

Leveraging ggplot2's strengths

You've seen you can add layers to a ggmap() plot by adding geom_***() layers and specifying the data and mapping explicitly, but this approach has two big downsides: further layers also need to specify the data and mappings, and facetting won't work at all.

Luckily ggmap() provides a way around these downsides: the base_layer argument. You can pass base_layer a normal ggplot() call that specifies the default data and mappings for all layers.

For example, the initial plot:

ggmap(corvallis_map) +
  geom_point(data = sales, aes(lon, lat))

could have instead been:

ggmap(corvallis_map, 
    base_layer = ggplot(sales, aes(lon, lat))) +
  geom_point()

By moving aes(x, y) and data from the initial geom_point() function to the ggplot() call within the ggmap() call, you can add facets, or extra layers, the usual ggplot2 way.

Let's try it out.

This exercise is part of the course

Visualizing Geospatial Data in R

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Use base_layer argument to ggmap() to specify data and x, y mappings
ggmap(corvallis_map_bw, ___) +
  geom_point(data = sales, aes(lon, lat, color = year_built))
Edit and Run Code