dictionary - Plotting barchart on States map in R -
following usa states example data state.x77 dataset in r:
mydf = structure(list(usa_state = structure(1:5, .label = c("alabama", "alaska", "arizona", "arkansas", "california"), class = "factor"), life.exp = c(69.05, 69.31, 70.55, 70.66, 71.71), hs.grad = c(41.3, 66.7, 58.1, 39.9, 62.6)), .names = c("usa_state", "life.exp", "hs.grad"), class = "data.frame", row.names = c(na, -5l)) > mydf usa_state life.exp hs.grad 1 alabama 69.05 41.3 2 alaska 69.31 66.7 3 arizona 70.55 58.1 4 arkansas 70.66 39.9 5 california 71.71 62.6 >
i want plot on usa states map. can plot map using following code:
all_states <- map_data("state") ggplot() + geom_polygon( data=all_states, aes(x=long, y=lat, group = group),colour="gray", fill="white" )
but not able plot barcharts on map. help.
i drew on 2 great sources answer this:
- http://www.r-bloggers.com/us-state-maps-using-map_data/. see gist https://gist.github.com/4252133 , comments @ end @amandamasonsingh (although gists demo prison dataset not available)
- ggplot/mapping counties — problems visualization shapes in r
solution
mydf <- structure(list(usa_state = structure(1:5, .label = c("alabama", "alaska", "arizona", "arkansas", "california"), class = "factor"), life.exp = c(69.05, 69.31, 70.55, 70.66, 71.71), hs.grad = c(41.3, 66.7, 58.1, 39.9, 62.6)), .names = c("usa_state", "life.exp", "hs.grad"), class = "data.frame", row.names = c(na, -5l)) library(ggplot2) library(maps) library(rcolorbrewer) # lots of color palettes these kind of charts library(data.table) # sorting key library(mapproj) #coord_maps() needed all_states <- map_data("state") # need merge dataset maps 1 long , lat. # need same key lets change state region used in maps all_states # note lowercased match mydf$region <- tolower(mydf$usa_state) totaldf <- merge(all_states, mydf, = "region") # switched data.table fix cut map issue # getting sort region order totaldt <- as.data.table(totaldf) setkey(totaldt, region, order) ggplot(data = totaldt, aes(x = long, y = lat, group = group, fill = hs.grad)) + geom_polygon() + coord_map() + scale_fill_gradientn("", colours=brewer.pal(9, "gnbu"))
dont forget sort me
if data not sorted correctly region , order, patchy maps this.
i use data.table
package , key data. data.table faster if need merge lots of data. use format x[y] this. see data.table cheatsheet if new package.
final map
this hs.grid
in example. other chart changing fill = myvariable
note not states shown, because test data limited these states. in fuller example see more states.
also see alaska missing. not in maps - see this answer @jazzurro practical tests on state names setdiff.
Comments
Post a Comment