Wednesday, 15 September 2010

r - Region polygons not displaying in ggplot2 Choropleth map -



r - Region polygons not displaying in ggplot2 Choropleth map -

i'm trying basic map plot ggplot2. can't find why colored polygons not display. seems code no different can find on many tutorials , questions answered on website. think come way prepare info (see 100% reproducible illustration below).

library(maptools) library(sp) library(ggplot2) library(rgeos) con <- url("http://biogeo.ucdavis.edu/data/gadm2/r/gha_adm1.rdata") print(load(con)) close(con) ghadf<-as.data.frame(gadm) ghadf$prod <- c(12, 26, 12,22,0,11,4,5,4,4) # add together values regions colored gadm@data$id = rownames(gadm@data) #create id in shapefile info ghamap <- fortify(gadm, region="id") colnames(ghadf[5])<-"id" ghamap <- merge(ghamap, ghadf) m0 <- ggplot(data=ghamap) m1 <- m0 + geom_polygon(aes(x=long, y=lat, fill = prod, group=group)) + scale_fill_gradient(low = "light green", high = "dark green") m2 <- m1 + geom_path(aes(x=long, y=lat, group=group),color='gray') + coord_equal() m2

on image above (the output of m2), regions should colored according ghamap$prod variable. suggestions?

(r version 3.0.2 - platform: x86_64-w64-mingw32/x64 (64-bit))

your problem simple. change

colnames(ghadf[5])<-"id"

to

colnames(ghadf)[5]<-"id"

and code produces map want.

the first line above extracts column 5 of ghadf info frame 1 column, sets column name "id", , discards when phone call colnames(...) completes. it not impact original info frame @ all.

the sec line extracts column names of ghadf character vector, , sets 5th element of vector "id", in effect changes name of column 5 of ghadf.

having said this, workflow bit tortured. 1 thing merging columns of gadm@data ghamap, unnecessary , extremely inefficient. code below produces same map:

load(url("http://biogeo.ucdavis.edu/data/gadm2/r/gha_adm1.rdata")) ghamap <- fortify(gadm) ghadf <- data.frame(id=rownames(gadm@data), prod=c(12,26,12,22,0,11,4,5,4,4)) ghamap <- merge(ghamap,ghadf) ggplot(ghamap, aes(x=long,y=lat,group=group))+ geom_polygon(aes(fill=prod))+ geom_path(color="gray")+ scale_fill_gradient(low = "light green", high = "dark green")+ coord_map()

r ggplot2 maps

No comments:

Post a Comment