Choropleth Map in ggplot2

[This article was first published on R – data technik, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 income:

This is great. The income has much more normal distribution. Seems varying among the states.

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.

To leave a comment for the author, please follow the link and comment on their blog: R – data technik.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)