Get startedGet started for free

sf plots with ggplot

You may also be familiar with the ggplot2 library, where a ggplot plot is made of several layers.

It turns out that sf objects can also be plotted using the ggplot2 library. As a quick revision, recall that the first layer is a blank canvas that's created by ggplot(). Subsequent layers are placed on top of each other by adding geom functions (which take the form geom_<plot>), labs(), themes and the like.

In the following, you will build a ggplot map using several sf objects.

The listings dataframe, a multipolygon called london_poly, and a collection of points called num_listings have also been loaded. The tidyverse and sf libraries have already been imported.

This exercise is part of the course

Building Dashboards with shinydashboard

View Course

Exercise instructions

  • Set the coordinates reference system (CRS) of num_listings to that of london_poly.
  • Add the multipolygon to the blank canvas.
  • Set the fill argument such that each neighborhood, as seen in the Name attribute, has a different fill.
  • Add a label at the center of each polygon.

Hands-on interactive exercise

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

# Set the CRS of num_listings to that of london_poly
st_crs(num_listings) <- ___(___)

# Add the multipolygon to the blank canvas
___ + 
  # Set a different fill for each neighborhood
  geom_sf(aes(___)) + 
  # Add a label at the center of each polygon
  ___(data=num_listings, aes(label=`Number of listings`)) +
  theme_classic()
Edit and Run Code