Skip to content

Instantly share code, notes, and snippets.

@benmarwick
Created April 16, 2018 07:32
Show Gist options
  • Save benmarwick/17c6dd5b3afc42c798871353aa81d96c to your computer and use it in GitHub Desktop.
Save benmarwick/17c6dd5b3afc42c798871353aa81d96c to your computer and use it in GitHub Desktop.
Plot a cartogram for the USA using crime data by joining a plain data frame to a SpatialPolygonsDataFrame
require(maps)
require(sp)
require(maptools)
require(tmap)
require(cartogram)
# get a SpatialPolygonsDataFrame of US states
usa <- map("state", fill = TRUE)
IDs <- sapply(strsplit(usa$names, ":"), function(x) x[1])
usa <- map2SpatialPolygons(usa, IDs=IDs, proj4string=CRS("+proj=longlat +datum=WGS84"))
usa <- SpatialPolygonsDataFrame(usa,
data = data.frame(unique(IDs),
row.names = unique(IDs)) )
# get a data frame of data with state names. Data here are crime rates,
# built-in dataset
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
# join data frame to the SpatialPolygonsDataFrame
# from https://stackoverflow.com/a/3652472/1036500
usa@data = data.frame(usa@data, crimes[match(usa@data[,'unique.IDs.'], crimes[,'state' ]),])
# make cartogram
crimes_ctgm <- cartogram(usa, "Murder", itermax=5)
# plot it
tm_shape(crimes_ctgm) +
tm_fill("Murder", style="jenks") +
tm_borders() +
tm_layout(frame=F)
@benmarwick
Copy link
Author

carto

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment