Choropleth Map in ggplot2

Creating a map in ggplot2 can be surprisingly easy! This tutorial will show the US by state. The dataset is from 1970 and will show some US statistics including population, income, life expectancy, and illiteracy.

I love making maps, while predictive statistics provide such great insight, map making was one thing that really made my interested in data science. I’m also glad R provides a great way to make them.

I’d also recommend plotly package where you can make it interactive as you scroll over. All within R!

Here is the first map we will make:

This is population by state in 1970 US.

library(ggplot2)
library(dplyr)

states<-as.data.frame(state.x77)
states$region <- tolower(rownames(states))
states_map <- map_data(“state”)
fact_join <- left_join(states_map, states, by = “region”)

ggplot(fact_join, aes(long, lat, group = group))+
geom_polygon(aes(fill = Population), color = “white”)+
scale_fill_viridis_c(option = “C”)+
theme_classic()

For the next graph the code will be mostly similar but I will change the fill = option.

Let’s try per capita income:

This is great. We’re able to see the income range through the color fill of each state.

ggplot(fact_join, aes(long, lat, group = group))+
geom_polygon(aes(fill = Income), color = “white”)+
scale_fill_viridis_c(option = “C”)+
theme_classic()

Last one we’ll make is life expectancy:

Great info here! Life expectancy, in the 1970s by state! That particular variable needed a little extra coding, see below:

fact_join$`Life Exp` <- as.numeric(fact_join$`Life Exp`)

ggplot(fact_join, aes(long, lat, group = group))+
geom_polygon(aes(fill = `Life Exp`), color = “white”)+
scale_fill_viridis_c(option = “C”)+
theme_classic()

Enjoy your maps! Also this dataset is publicly available so feel free to recreate.

One thought on “Choropleth Map in ggplot2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s