Ari Lamstein did a 5-week email course on how to map census data in R. This is my attempt to create a single page version of the entire course.

The R Package choroplethr is used for this exercise.

Installation of the required libraries

install.packages("choroplethr")
install.packages("choroplethrMaps")

The library comes with some datasets. The dataset df_pop_state has population by state, and the dataset df_state_demographics has some demographic information by state. Now, let’s load these two datasets

library(choroplethr)
data(df_pop_state)
data(df_state_demographics)

Our first choropleth

This is as simple as calling the state_choropleth function from the choroplethr library.

state_choropleth(df_pop_state, title="2012 Population by State", legend="Population")

Let’s try to look at those states whose population is less than 1 million.

To do the data munging, let’s use the dplyr package.

library(dplyr)
## 
## Attaching package: 'dplyr'
## 
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## 
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
#Create two dataframes- one of states with less than 1 million population
#and another of states with more than 1 million population

states_w_less_than_1m <- df_pop_state %>%
  filter(value < 1000000) %>% 
  mutate(value="<1M")

states_w_more_than_1m <- df_pop_state %>%
  filter(!(region %in% states_w_less_than_1m$region)) %>%
  mutate(value=">1M")

#Merge the above two dataframes
states_pop_seg_by_million <- data.frame(rbind(states_w_more_than_1m, states_w_less_than_1m))

state_choropleth(states_pop_seg_by_million)