1. Plotting data with tigris and ggplot2
ggplot2 includes a geom_sf() function for plotting simple features objects. This allows you to make maps using familiar ggplot2 syntax! In this lesson, you'll learn how to create a map of Texas legislative districts by political party affiliation using ggplot2 step-by-step.
2. Plotting spatial data with geom_sf()
The geom_sf() function in ggplot2 works much like other geom_ functions available in the package. After initializing the ggplot object with the ggplot() function, geom_sf() without any arguments can be used to visualize the geography of spatial datasets quickly. Here, we can see Texas's legislative district boundaries; districts tend to be larger in area in rural west Texas, and smaller in and around Texas's large cities of Houston, Dallas-Fort Worth, Austin, and San Antonio.
3. Setting the fill aesthetic for regions
As we joined some contextual information to our legislative district dataset in the previous lesson, we can use this information to make a map. geom_sf() understands a fill aesthetic for areal, or polygon, data, so we can tell ggplot2 to modify the fill of legislative districts by the Party value, which will be either D for Democratic or R for Republican, the two main political parties in the United States. This allows us to examine some patterns in Texas; areas in large cities and along the US-Mexico border tend to be represented by members of the Democratic party, whereas the rest of Texas tends to be represented by members of the Republican party.
4. Customizing fill colors
However, this color scheme doesn't make much sense for analysts familiar with American politics. In the United States, the Democratic party is commonly associated with the color blue, and the Republican party is associated with the color red. To modify this, we can add a call to the scale_fill_manual() function and pass to it a named vector of values, telling ggplot2 to color republican areas red and democratic areas blue.
5. Polishing up the output
Before sharing your map with others, you'll likely want to make a few more modifications to the map. The code on the slide includes a call to coord_sf() to modify the displayed coordinate system to one appropriate for Texas. In addition, the datum equals NA argument will remove the gridlines from behind the map. We then set the theme to minimal to get a white background and give the map an informative title.
6. Our final map
We now have our result: an informative map of Texas House of Representatives legislative districts colored by their representatives' parties of affiliation.
7. Let's practice!
Now, it's your turn to make this map yourself with R and ggplot2!