1

I would like to create visual maps of congressional districts within R. I would like to give it data on the number of people voting in each district and make a heat map by district as a visual via R.

Here are some generic examples of state maps divided by congressional district (without voting data or a heat map) but I would want to create a fairly minimalistic map to plot off of so these are similar in feel to what I want to create:

  1. Texas
  2. Minnesota

Here is some sample code for a base map in R, outlining the congressional districts:

library(USAboundariesData) # Needed for us_congressional()
library(sf) # Needed for st_geometry()

mn_congressional <- us_congressional(states = "Minnesota", resolution = "high")
plot(st_geometry(mn_congressional))

However, I now want to incorporate this with a column of voting totals for each of the districts and color the district sections in this map as a heat map?

Bear
  • 662
  • 1
  • 5
  • 20
  • 2
    Don't reinvent the wheel: see `USAboundaries::us_congressional(resolution = "high", states = c("Texas", "Minnesota"))` – Mako212 Oct 31 '18 at 19:04
  • @Mako212 I updated my question including your suggestion to get the blank layout for the state. – Bear Oct 31 '18 at 19:43
  • Please provide a sample of the data you'd like to incorporate – Mako212 Oct 31 '18 at 19:47

1 Answers1

2

This method is pretty easy to add data to.

library(ggplot2)
library(USAboundaries)

cd_mn <- USAboundaries::us_congressional(resolution = "high", states = c("Minnesota"))
cd_mn$Voters <- runif(length(cd_mn$geometry), 500, 5000) #create some random data for the number of districts

ggplot(cd_mn) + geom_sf(aes(fill = Voters)) +
  scale_fill_gradientn(colors = rev(heat.colors(5)))

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29
  • 1
    And for OP to match his/her data to the map, they need to match by the district number in the `cd115fp` column. – Mako212 Oct 31 '18 at 19:53
  • Is there a different package for `geom_sf`? I am getting an error: `could not find function "geom_sf"` – Bear Oct 31 '18 at 20:17
  • 1
    It should be in `ggplot2`, but see if [this answer](https://stackoverflow.com/questions/46185226/error-when-plotting-sf-object-error-could-not-find-function-geom-sf) solves it. I am using `ggplot2` version 3.0.0. – Anonymous coward Oct 31 '18 at 20:20
  • It was a version issue on my end, updated and code now runs. – Bear Oct 31 '18 at 20:51