Optional task 1: Map presidential elections results with maps package
Try to make a map in 2000
##Task1
load("D:/AAEC8610/HW5/1976-2016-president.RData")
library(maps)
library(RColorBrewer)
library(dplyr)
Vote<-select(x,year,state,state_fips,party,candidate,candidatevotes)
maxVote<-Vote %>% group_by(state,year) %>% top_n(1,candidatevotes)
maxVote$col <- ifelse(maxVote$party=="democrat", "#0000FF" , ifelse(maxVote$party=="republican", "#FF0033", "#FFFFFF"))
maxVote2000<-maxVote[maxVote$year==2000,c("state_fips","party","col")]
maxVote2000<-maxVote2000[match(paste(state.fips$fips),paste(maxVote2000$state_fips)),]
map("state",col=maxVote2000$col,fill=TRUE)Loop the code and map it over time
#Make a arithmetric sequence with the length of 4
years=seq(1976,2016,by=4)
#Layout matrix for place
top<-matrix(c(rep(1,9),rep(2,9),rep(3,9)),nrow=3,ncol=9)
top2<-matrix(c(rep(4,9),rep(5,9),rep(6,9)),nrow=3,ncol=9)
bot<-matrix(c(rep(7,9),rep(8,9),rep(9,9)),nrow=3,ncol=9)
bot2<-matrix(c(rep(10,9),rep(11,9),rep(12,9)),nrow=3,ncol=9)
m<-rbind(top,top2,bot,bot2)
layout(m)
par(mar=c(1,1,1,1),oma=c(0,0,0,0),bg="grey")
for (i in years){
temp<-maxVote[maxVote$year==i,c("state_fips","party","col")]
temp<-temp[match(paste(state.fips$fips),paste(temp$state_fips)),]
map("state",col=temp$col,fill=TRUE)
mtext(i,side=3,line=1)
}
plot(0, axes=F, xlab="",ylab="", type="n")
#box.lty=0 there is no border in the legend
#1: normal; 2: bold; 3:italic; 4: bold and italic
legend("bottom",legend=c("Republican","Democrat","Other"),fill=c("#FF0033", "#0000FF","#FFFFFF"), horiz=F, cex=1, border=T,
box.lty=1)
mtext("Presidental election results ",cex=0.8,line=1.4, font=2)
mtext("by state and year",cex=0.8,font=2)Optional task 2: Interactive maps with leaflet
Make maps with leaflet package
Guangzhou Tower
library(leaflet)
myMap<-leaflet()%>%
addProviderTiles(providers$OpenStreetMap)%>%
setView(lat=23.106228,lng = 113.323646,zoom=15)
myMapRohingya Refugee Camps
library(sf)
library(shapefiles)
sp<-read_sf("190310_outline_rohingya_refugee_campblock_a2/190310_Outline_Rohingya_Refugee_CampBlock_A2.shp")
campShapeFile<- sp %>%
st_transform(4326)
#head(campShapeFile)
leaflet() %>%
addProviderTiles(providers$Esri.WorldStreetMap)%>%
setView(92.14871,21.18780,zoom=12) %>%
addPolygons(data=campShapeFile,fill=TRUE,stroke=T,weight=1,highlight = highlightOptions(fillOpacity = 0.7),
label =campShapeFile$Block_No)A Raster Image of Rainfall
library(maps)
myMap2 <- map("state", fill = TRUE,plot=FALSE)
leaflet(data = myMap2) %>% addTiles() %>%
addPolygons(fillColor = topo.colors(20, alpha = 0.8),stroke=T,weight=0.5) %>%
addWMSTiles(
"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
layers = "nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "Weather data © 2012 IEM Nexrad"
)