问题
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:
- Texas
- 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?
回答1:
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)))
来源:https://stackoverflow.com/questions/53090122/create-a-congressional-district-map-of-a-state-in-r