Session Ready
Exercise

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.

Instructions 1/2
undefined XP
  • 1
  • 2

Rewrite the first plot to use the base_layer argument of ggmap().

  • Add a base_layer argument to the ggmap() call.
  • This should call ggplot().
  • Move the data and x and y mappings out of geom_point(). Leave the color argument inside the aes() function within your geom_point() call.