简体   繁体   中英

US Choropleth map in R

I have read virtually every google link to try and make one of these.

I am using gtd dataset ( http://www.start.umd.edu/gtd/contact/ )

What I am trying to do is color the states of the US map based on the number of attacks that have occurred in that state, using the maps package.

Based on codes I have seen, I know I need to match the names from my data to the names in the map package, and then pick the data to plot based upon.

US<- subset(x=gtd, country_txt="United States")
stateattacks<- ddply(US, .(provstate), "nrow")
data(state) 
mapnames<- map("state", plot=FALSE)$names
region_list<- strsplit(mapnames, ":")
mapnames2<- sapply(region_list, "[", 1)
m<- match(mapnames2, tolower(stateattacks$provstate)
map.area <- nrow[m] #nrow is the variable I am trying to match.. but this step gives Error in nrow[m] : object of type 'closure' is not subsettable. 

I am just trying to map each states color based on the number of attacks in that state (nrow) but I can't get it configured.

Back in the "old days" these choropleths took some work in R but with the choroplethr package by the fine folks at Trulia, it's far easier than it should be in R (at least for US choropleths):

library(choroplethr)

gtd <- read.csv("gtd.csv")

US <- gtd[gtd$country_txt == "United States",]

stateattacks<- ddply(US, .(provstate), "nrow")

# choroplethr needs these column names
colnames(stateattacks) <- c("region", "value")

# choroplethr might do this internally (have not checked)
# but it's not a bad thing to do anyway
stateattacks$region <- tolower(stateattacks$region)

# it won't work with the (…) bit and that might have been your 
# problem with "old school' chorpleths not working
stateattacks$region <- gsub(" (u.s. state)", "", stateattacks$region, fixed=TRUE)

# make the US choropleth
choroplethr(stateattacks, lod="state")

在此处输入图片说明

Plenty of customization options in the package.

A choropleth for this particular situation is probably fine, but for other types of data, it's usually a good idea to consider normalizing for population, otherwise it can skew the message improperly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM