Get startedGet started for free

Spatial Data

1. Plotting Polygons

So far in the course, we have focused on plotting points using a latitude longitude coordinate pair. There are several additional spatial features we can map, like polygons.

2. Spatial Data

We stored point coordinates and information describing the point in a single row of the data frame. This was sufficient for points with each row representing a single point. However, polygons have many points, which would require us to have the data repeat. Rather than repeating the information that describes the polygon across multiple rows, we can leverage a different type of object from the sp package called the spatial polygons data frame.

3. SpatialPolygonsDataFrame

Let's use RStudio's object viewer to take a look at a spatial polygons data frame called shp. This data frame contains information on North Carolina zip codes. You'll notice that there are five slots in the shp object: data, polygons, plotOrder, bbox, and projection string.

4. SpatialPolygonsDataFrame

The data slot has one observation for each polygon. The polygons slot holds the coordinates needed to plot each polygon. The plot order slot describes the order for plotting each of the polygons. The bounding box describes the rectangle that all of the polygons fit within. And lastly, the projection string contains the coordinate reference system.

5. Working with Spatial Data in R

Let's take a closer look at the data slot. You can access the information in any of the five slots using the @ symbol. The data slot in this example stores zip codes and the area of each polygon. Since the information in the data slot is stored as a data frame, we can join on additional variables using dpylr. For instance, we can join on income information from the IRS including the mean income per zip code.

6. Working with Spatial Data in R

This works just like joining any two data frames and yields a data frame in the data slot with five variables and 808 observations.

7. Our SpatialPolygonsDataFrame

In the exercises, you will use income information to color zip codes by mean income, but first let's take a look at a single polygon. Similar to how we mapped points, we can pipe our polygon data into a call to leaflet(). Then instead of using addMarkers(), we can use addPolygons(). If we want to add more context to our map, we can plot this zip code on top of a base map just like we did when mapping colleges.

8. Let's practice!

Now it's your turn to explore a spatial polygons data frame.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.