I am struggling to create a congressional heat map using the ggplot2 and sf libraries.
So far I can create blank maps of state congressional districts:
library(ggplot2)
library(fiftystater)
library(colorplaner)
library(USAboundaries)
library(sf)
#This is where I'm pulling congressional district data from
data('us_congressional')
#Creating dummy data
us_congressional <- us_congressional(resolution = c("low", "high"), states =
NULL)
us_congressional$dummy <- runif(nrow(dftest), 1, 100)
#Selecting certain states to plot
plot_states_data <- us_congressional(states=c("Maine", "Minnesota", "New
York", "California", "Montana", "Illinois", "Florida", "Texas"), resolution
= 'high')
plot(st_geometry(plot_states_data))
I'd like to be able to tie the dummy data to the blank plotted shapes and fill on a gradient - something like this:
#These don't work
ggplot(st_geometry(plot_states_data)) + geom_sf(aes(fill=dummy)) +
scale_fill_gradient2(low='red',mid = 'white', high = 'blue', midpoint = 50)
# or
plot(st_geometry(plot_states_data)) + geom_sf(aes(fill=dummy)) +
scale_fill_gradient2(low='red',mid = 'white', high = 'blue', midpoint = 50)
But I run into an error: "could not find function "geom_sf"" when using the plot command and this error: "ggplot2 doesn't know how to deal with data of class sfc_MULTIPOLYGON/sfc" when using the ggplot command.
I think the issue is that plot_states_data is both a data frame and sf object class and I am unsure how to either make plot_states_data just a data frame or how to make ggplot and sf work together.
Does anyone have any suggestions on working around these problems?
Edit:
austensen's comment on downloading the developer ggplot2 has solved the problem. For anyone else trying to do the same kind of mapping, this command did the trick for me:
ggplot(plot_states_data) + geom_sf(aes(fill=dummy)) +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
scale_fill_gradientn("Title",
colours = c('darkred', 'tomato1', 'cyan2',
'darkblue'),
values = c(0,.5,.5000001, 1)) +
theme(panel.background = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank())