Assigning specific colors to polygons in a shapefile using R -
i comparing results of 2010 , 2014 mid-term elections in state of virginia. doing using file has virginian congressional districts on map of virginia. want color districts elected republican canidate reddish , color districts elected democratic canidate blue. there more project 1 time figure out how 1 thing able figure out how go rest of project.
i using files found here:
http://www.arcgis.com/home/item.html?id=dc20260d27654c64bfa0c2979a317597
this code using plot shapefile:
library(maptools) library(shapefiles) ccbound <- readshapepoly("tl_rd13_51_cd113") ccbound2 <- ccbound system.time(plot(ccbound2)) this gives me nice map of virginia 10 congressional districts outlined.
how should go coloring in districts stated above?
here's ggplot solution. seem asking base of operations r method, imo it's worthwhile larn ggplot added flexibility. should started.
i had create assumptions format of data, since didn't provide it. code below shows how info organized in example
# 2010 , 2014 congressional election results in virginia. data.2010 <- data.frame(district=sprintf("%02i",1:11), r=c(63.9,53.1,27.2,62.3,50.8,76.3,59.2,37.3,51.2,62.9,48.8), d=c(34.8,42.4,70.0,37.5,47.0,00.0,34.1,61.0,46.4,34.8,49.2)) data.2014 <- data.frame(district=sprintf("%02i",1:11), r=c(63.0,57.9,000.0,60.3,61.0,75.5,60.9,31.7,74.9,56.6,40.4), d=c(34.5,42.1,100.0,37.5,35.8,00.0,36.9,63.0,00.0,40.4,56.9)) info <- cbind(year=rep(c(2010,2014),each=11),rbind(data.2010,data.2014)) data$delta <- with(data,d-r) head(data) # year district r d delta # 1 2010 01 63.9 34.8 -29.1 # 2 2010 02 53.1 42.4 -10.7 # 3 2010 03 27.2 70.0 42.8 # 4 2010 04 62.3 37.5 -24.8 # 5 2010 05 50.8 47.0 -3.8 # 6 2010 06 76.3 0.0 -76.3 this plots maps.
library(ggplot2) library(rgdal) setwd("c:/users/jlh/desktop/map/virginia.congressional.districts") map <- readogr(dsn=".",layer="tl_rd13_51_cd113") map.data <- data.frame(id=rownames(map@data),district=map@data$cd113fp) map.data <- merge(map.data,data) map.df <- fortify(map) map.df <- merge(map.df,map.data) ggplot(map.df,aes(x=long,y=lat,group=group))+ geom_polygon(aes(fill=delta),color="grey20")+ facet_wrap(~year,nr=2)+ scale_fill_gradient2(low="red",high="blue",mid="white",limits=c(-100,100))+ coord_map()+labs(x="",y="")+ theme_bw()+ theme(panel.grid=element_blank(), panel.border=element_blank(), axis.text=element_blank(), axis.ticks=element_blank()) note in 2014 in 3rd district democrat ran unopposed, while 6th , 9th districts contested, there no democrat running.
the posts here, , here have explanation of workflow.
r colors shapefile
No comments:
Post a Comment