Reputation: 3125
I think I just made the world's weirdest choropleth.
The code is simple:
df$cut <- cut_interval(df$Count, 5)
ggplot(df, aes(lon, lat)) +
geom_polygon(aes(fill = df$cut), colour = alpha("white", 1/2), size = 0.2) +
geom_polygon(data = df , colour = "white", fill = NA) +
scale_fill_brewer(palette = "PuRd")
(see Pastebin for a dput
of the dataframe)
But the map is crazy:
Where did I go wrong?
Looking at other code snippets, I can't seem to figure out how to make this work.
Upvotes: 0
Views: 260
Reputation: 54237
You could plot a choropleth like this:
library(ggplot2)
library(XML)
tab <- readHTMLTable("http://www.50states.com/abbreviations.htm", which=1)
df$region <- tolower(tab[match(df$State, tab[, 2]), 1])
states <- map_data("state")
choro <- merge(states, df, sort = FALSE, by = "region")
choro <- choro[order(choro$order), ]
ggplot(choro, aes(long, lat.x)) +
geom_polygon(aes(group = group, fill = Count), colour="grey55") +
coord_quickmap() +
facet_wrap(~Year)
First, you gotta match the region names in your df$State
to the ones in states$region
. Then, the map data is merged with your data frame and put in order. Finally, the plot is a piece of cake using ggplot.
Upvotes: 1