Get startedGet started for free

Putting it all together

You now have a nice map of Corvallis, but how do you put the locations of the house sales on top?

Similar to ggplot(), you can add layers of data to a ggmap() call (e.g. + geom_point()). It's important to note, however, that ggmap() sets the map as the default dataset and also sets the default aesthetic mappings.

This means that if you want to add a layer from something other than the map (e.g. sales), you need to explicitly specify both the mapping and data arguments to the geom.

What does this look like? You've seen how you might make a basic plot of the sales:

ggplot(sales, aes(lon, lat)) + 
  geom_point()

An equivalent way to specify the same plot is:

ggplot() + 
  geom_point(aes(lon, lat), data = sales)

Here, we've specified the data and mapping in the call to geom_point() rather than ggplot(). The benefit of specifying the plot this way is you can swap out ggplot() for a call to ggmap() and get a map in the background of the plot.

This exercise is part of the course

Visualizing Geospatial Data in R

View Course

Exercise instructions

The ggmap package has been loaded for you and corvallis_map from the previous exercise is available in your workspace.

  • First, take a look at the head() of the sales data. Can you see the columns specifying the location of the house?
  • Swap out the call to ggplot() with a call to ggmap() with corvallis_map.

Hands-on interactive exercise

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

# Look at head() of sales


# Swap out call to ggplot() with call to ggmap()
ggplot() +
  geom_point(aes(lon, lat), data = sales)
Edit and Run Code