Maps with ggplot2: Plotting Geospatial Data
The beauty of ggplot2 is that it treats geographic shapes just like any other aesthetic mapping. By using the specialized geom_sf() layer, you can turn spatial data objects into beautiful, layered maps with the same "grammar" you already know.
In this lesson, you’ll learn how to visualize spatial data by plotting polygons, points, and lines. We’ll cover how to map variables to fill colors to create choropleth maps, how to handle multiple spatial layers on a single canvas, and how to change the projection of your map.
😌 Simple, Yet Versatile
The Simple Features concept, which stores all the spatial information in an (almost) regular rectangular format, perfectly fits the needs of ggplot2. Thanks to this concept and its implementation in the sf 📦, you can draw maps like any regular chart, such as a standard scatterplot or a time series.
Even better: because we're talking about coordinates, positional mappings to x and y are pre-defined anyway!
This makes it possible to draw all the information with a single layer: geom_sf() acts as a "chameleon". You don't have to switch functions for different geometry types: no matter whether the coordinates represent points, lines, or polygons, the same function handles them all.
Let's start demonstrating the "one-geom-fits-all" approach by visualizing the and creating a world map:
Note: Because our interactive sandbox requires a two-step download, we use download.file() before reading it into R. In your local R setup, you can simply pass the URL directly into st_read()!
Nice, we have drawn our first map 👐 As we pass an sf object with polygons, geom_sf() draws areas with a fill and an outline with a color and linewidth.
🧭 Map Some Data
But let's visualize some of the variables in our data. As usual, we can map a variable to thefill aesthetic to create either a classic choropleth map or color by some categories:
🐉 A True Chameleon
(refers to the geom, not the emoji)
For now, we have only used spatial data stored as polygons. But as you've learned, there are multiple types of vector data that can be stored as "simple features", namely points and lines (along with multi-points, multi-lines, and multi-polygons).
To showcase the "chameleon behavior" of geom_sf(), let's load the coordinates of all capitals around the world and plot them with the same function:
Doors are closed 🚪
Enrollment for the current cohort is closed. Join the waitlist to be notified as soon as the next cohort opens, and become the ggplot2 expert your company needs!
Already enrolled? Login