Happy Pride Month!!! Although 2020 has been emotionally taxing, we now have something big to celebrate. This week, the Supreme Court ruled that the 1964 Civil Rights Act protects gay, lesbian, and transgender employees from discrimination. About time!
If you’re celebrating Pride from home and want a rainbow-themed R project while you binge Netflix’s Pride collection, we’ve got you covered! In this tutorial, we’ll be coloring the map of the contiguous United States to make it a look a little more festive.
Loading libraries and data
The map_data( ) function takes data from the ‘maps’ package and turns it into a data frame. Unfortunately, the state data doesn’t include Alaska and Hawaii.
# Load libraries. library(ggplot2) library(ggmap) library(arules) # Grab state data. states <- map_data("state")
Specifying colors by longitude
If we want to color the map vertically, we’ll need to group states by longitude. First, we’ll find the average longitude of each state. Then, we’ll split these averages into six chunks where each chunk represents a different color of the rainbow.
# Find average longitude of each state. meanLong <- tapply(states$long, states$region, mean) # Discretize average longitude into desired number of intervals # and specify color for each interval. longByRainbow <- discretize(meanLong, breaks = 6, method = "cluster", labels = c("#8748A3", "#25AEE4", "#52DD3A", "#FFEB12", "#FE7B20", "#FE1417"))
Plot that beauty!
# Plot. ggplot(data = states) + geom_polygon(aes(x = long, y = lat, fill = region, group = group), color = "white") + scale_fill_manual(values = as.vector(longByRainbow)) + coord_fixed(1.3) + guides(fill=FALSE) + # do this to leave off the color legend theme_nothing()
Can you re-create this map?
D. Kahle and H. Wickham. ggmap: Spatial Visualization with ggplot2. The R Journal, 5(1), 144-161.