Rshp filesshp files on the web:https://github.com/Groupe-ElementR/FreeCarto/tree/master/SCRIPTS/data
.prj, .sbn, sbx, .shp, .shp.xml, shx files and put them in the same directory.shp into R> library(maptools)
> library(sp)
> library(shapefiles)
> fdc <- readShapePoly("/Users/dhafermalouche/Documents/Teaching/AdvancedR/geom/Tunisie_snuts4.shp")shp into R> plot(fdc)shp into Rraster package> library(raster)
> fdc0<- getData(name="GADM", country="TUN", level=0)raster package> plot(fdc0)raster package> fdc1<- getData(name="GADM", country="TUN", level=1)> plot(fdc1)> fdc2<- getData(name="GADM", country="TUN", level=2)> plot(fdc2)googleVisR> library(googleVis)
> library(readr)
> library(rgdal)
> op <- options(gvis.plot.tag="chart")
> tn <- read_delim("/Users/dhafermalouche/Documents/Teaching/AdvancedR/tunisie_data_del_2011.csv",
+ ";", escape_double = FALSE, trim_ws = TRUE)
> colnames(tn)
[1] "del" "del_nom" "gou" "gou_nom" "reg"
[6] "reg_nom" "zon" "zon_nom" "cap_gou" "POPTO2004"
[11] "POPCO2004" "NBLOG2004" "IMMIG9404" "EMIG9404" "POPTO2010"
[16] "SUP2010" "IDRVA2011"html code (only gouvernorat)> g1 <- gvisGeoChart(tn, locationvar = "gou",hovervar = "gou_nom",
+ options=list(region="TN",
+ displayMode="regions",
+ resolution="provinces",
+ width=800, height=600))
> print(g1, file="g1.html")
> cat(g1$html$chart, file = "g1.html")html code (only gouvernorat)leaflet package> library(leaflet)
> mm<-leaflet(data = fdc2) %>%
+ addProviderTiles("CartoDB.Positron")%>%
+ addPolygons(fillColor = "#444444",
+ weight = 1,
+ smoothFactor = 0.5,
+ opacity = 1.0, fillOpacity = 0.5,
+ highlightOptions = highlightOptions(color = "white",
+ weight = 2,
+ bringToFront = TRUE))leaflet package> mypopup=fdc2$NAME_2
> mm<-leaflet(data = fdc2) %>%
+ addProviderTiles("CartoDB.Positron")%>%
+ addPolygons(fillColor = "red",
+ color="black",
+ weight = 1,
+ smoothFactor = 0.5,
+ popup = mypopup,
+ opacity = 0.5, fillOpacity = 0.5,
+ highlightOptions = highlightOptions(color = "white",
+ weight = 2,
+ bringToFront = TRUE))ggplot2> library(ggplot2)
> tun_df <- fortify(fdc,region = "id")
> colnames(tun_df)
[1] "long" "lat" "order" "hole" "piece" "id" "group"ggplot2> p<-ggplot(tun_df, aes(x=long, y=lat, group=group)) +
+ geom_polygon(aes(fill="pink"),color = "grey50")+
+ labs(x="",y="")+ theme_bw()+
+ coord_fixed()
> p<-p+theme(axis.line=element_blank(),
+ axis.text.x=element_blank(),
+ axis.text.y=element_blank(),
+ axis.ticks=element_blank(),
+ axis.title.x=element_blank(),
+ axis.title.y=element_blank(),
+ panel.grid.major = element_blank(),
+ panel.grid.minor = element_blank(),
+ panel.border = element_blank(),
+ panel.background = element_blank())
> p<-p+ theme(legend.position="none")ggplot2Representing populations by delegation
> data_del <- read.csv("tunisie_data_del_2011.csv", header = TRUE, sep = ";",
+ dec = ",", encoding = "latin1")fdc object of the slide #3> pt <- cbind(fdc@data[, "id"], as.data.frame(coordinates(fdc)))
> dim(pt)
[1] 263 3pt (containing the coordinates) and the data containing the variable> colnames(pt) <- c("id", "x", "y")
> i=match(pt[, "id"], data_del[, "del"])
> pt <- data.frame(pt, data_del[i, ])
> pt$var <- pt$POPTO2010bbox function gives the max and min coordinates of the base map> x1 <- bbox(fdc)[1]
> y1 <- bbox(fdc)[2]
> x2 <- bbox(fdc)[3]
> y2 <- bbox(fdc)[4]> M <- (x2 - x1) * (y2 - y1)> sc <- sum(pt$var, na.rm = TRUE)
> sc
[1] 10489116\[r_i=\sqrt{\displaystyle\frac{kx_iM}{s\,\pi}}\] Hence the area of one circle is \(a_i=\pi r_i^2= \pi \displaystyle\frac{kx_iM}{s\,\pi}=\displaystyle\frac{kM}{s}x_i\)
Then \(\sum_i a_i= kM\), we choose \(k=.2\) (20% of the total surface of the map)
> k <- 0.2
> pt$size <- sqrt((pt$var * k * M/sc)/pi)> plot(fdc, border = "white", col = "grey")
> symbols(pt[, c("x", "y")], circles = pt$size, add = TRUE, bg = "red", inches = FALSE)> LegTitle <- "Popuplation"> rLeg <- quantile(pt$size, c(1, 0.9, 0.25, 0), type = 1, na.rm = TRUE);rLeg
> rVal <- quantile(pt$var, c(1, 0.9, 0.25, 0), type = 1, na.rm = TRUE);rVal
> l <- data.frame(x = x1, y = y1)
> head(l)> xinit <- l$x + rLeg[1]
> xinit
> ypos <- l$y + rLeg
> ypos> symbols(x = rep(xinit, 4), y = ypos, circles = rLeg,
+ add = TRUE, bg = "red",
+ inches = FALSE)
>
> text(x = rep(xinit, 4) + rLeg[1] * 1.2, y = (l$y + (2 * rLeg)), rVal, cex = 0.3,
+ srt = 0, adj = 0)> for (i in 1:4) {
+ segments(xinit, (l$y + (2 * rLeg[i])), xinit + rLeg[1] * 1.1, (l$y + (2 *
+ rLeg[i]))) }
> text(x = xinit - rLeg[1], y = (l$y + (2 * rLeg[1])), LegTitle, adj = c(0, 0),
+ cex = 0.7)> title(main = "Population, 2010", cex.sub = 0.7)> xscale <- x2
> yscale <- y1
> sizescale <- 50000
> labelscale <- "50km"
> SpatialPolygonsRescale(layout.scale.bar(), offset = c(xscale, yscale), scale = sizescale,
+ fill = c("black"), plot.grid = F)
> text(xscale + sizescale/2, yscale, paste(labelscale, "\n\n", sep = ""), cex = 0.7)> xarrow <- x1
> yarrow <- y2 - (y2 - y1)/10
> SpatialPolygonsRescale(layout.north.arrow(2), offset = c(xarrow, yarrow), scale = 50000,
+ plot.grid = F)plot> i=match(fdc@data[, "id"], data_del[, "del"])
> fdc@data <- data.frame(fdc@data, data_del[i,])
> colnames(fdc@data)
[1] "id" "id_snuts3" "id_snuts2" "id_snuts1" "id_snuts0"
[6] "del" "del_nom" "gou" "gou_nom" "reg"
[11] "reg_nom" "zon" "zon_nom" "cap_gou" "POPTO2004"
[16] "POPCO2004" "NBLOG2004" "IMMIG9404" "EMIG9404" "POPTO2010"
[21] "SUP2010" "IDRVA2011"
> summary(fdc@data$IDRVA2011)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.0000 0.1885 0.3120 0.3179 0.4220 1.0000 > summary(fdc@data$IDRVA2011)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.0000 0.1885 0.3120 0.3179 0.4220 1.0000 plot> nbclass <- 8
> var<-fdc@data$IDRVA2011
> library(classInt)
> distr <- classIntervals(var, nbclass, style = "quantile")$brks
> library(RColorBrewer)
> colours <- brewer.pal(nbclass, "YlOrRd")
> colMap <- colours[(findInterval(fdc@data$IDRVA2011, distr, all.inside = TRUE))]plot> plot(fdc, col = colMap, border = "black", lwd = 1)plotplot> legend(x = "topright",
+ legend = leglabs(round(distr, 2),
+ over = "plus de", under = "moins de"),
+ fill = colours, bty = "n", pt.cex = 1,
+ cex = 0.7, title = "indice 0-1")
> title(main = "Regional Developpment Index",
+ cex.sub = 0.7)plotR> library(readr)
> data_delegation_tunisia <- read_csv("data_delegation_tunisia.csv")del (delegation codes), Nahdha_2011 and Nahdha_2014. Let’s extract them!> dt=data_delegation_tunisia[,c("del","Nahdha_2011","Nahdha_2014")]fdc (see slide 4)> i=match(fdc@data$id,dt$del)
> fdc@data$Nahdha_2014=dt$Nahdha_2014[i]
> fdc@data$Nahdha_2011=dt$Nahdha_2011[i]Imputing missing values (to discussed)
> library(e1071)
Attaching package: 'e1071'
The following object is masked from 'package:raster':
interpolate
> x=matrix(fdc@data$Nahdha_2014,ncol=1)
> x=impute(x)
> fdc@data$Nahdha_2014=x
> y=matrix(fdc@data$Nahdha_2011,ncol=1)
> y=impute(y)
> fdc@data$Nahdha_2011=yggplot2: data for polygons> library(ggplot2)
> tun_df <- fortify(fdc,region = "id")
> dim(tun_df)
[1] 3490 7> library(reshape2)
> dt=fdc@data[,c(1,6,7)]
> colnames(dt)=c("id","2014","2011")
> dt=melt(dt,id.vars = "id")
> colnames(dt)=c("id","Year","Votes")
> tun_df_all=merge(tun_df,dt,by="id")
> colnames(tun_df_all)
[1] "id" "long" "lat" "order" "hole" "piece" "group" "Year" "Votes"> library(RColorBrewer)
> p<-ggplot(tun_df_all, aes(x=long, y=lat, group=group)) +
+ geom_polygon(aes(fill=Votes),color = "grey50")+
+ scale_fill_gradientn(colours=brewer.pal(5,"OrRd"),name="Votes")+
+ labs(x="",y="")+ theme_bw()+facet_grid(~Year)+
+ coord_fixed()> p<-p+theme(axis.line=element_blank(),
+ axis.text.x=element_blank(),
+ axis.text.y=element_blank(),
+ axis.ticks=element_blank(),
+ axis.title.x=element_blank(),
+ axis.title.y=element_blank(),panel.grid.major = element_blank(),
+ panel.grid.minor = element_blank(),
+ panel.border = element_blank(),
+ panel.background = element_blank())
> p<-p+ theme(legend.position="right")
> pDifference variablespplot package from lattice package (All delegations)> library(lattice)
> fdc@data$Difference=fdc@data$Nahdha_2014-fdc@data$Nahdha_2011
> spplot(fdc,"Difference",
+ main="Difference of number of voters\n 2014 and 2011",sub="")Difference variableWe will display the delegations where Nahdha party gained voters (positive)
> i=which(fdc@data$Difference>0)
> spplot(fdc[i,],"Difference",main="Difference of number of voters\n 2014 and 2011",sub="")Leaflet packagefdc2 object import in the slide 13> i=match(fdc2$HASC_2,data_delegation_tunisia$HASC_2)
> fdc2a=cbind.Spatial(fdc2,data_delegation_tunisia[i,])> xv=fdc2a@data$taux.de.chomage.en.2004
> summary(xv)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
4.50 10.60 14.50 15.34 19.10 39.00 15 Leaflet package> library(leaflet)
> MyPaletteColor <- colorQuantile("YlGn", NULL, 7)> my_popup <- paste0("<strong>",fdc2a@data$delegation,"</strong>",xv,"%")leaflet> mm<-leaflet(data = fdc2a) %>%
+ addProviderTiles("CartoDB.Positron") %>%
+ addPolygons(fillColor = ~MyPaletteColor(xv),
+ fillOpacity = 0.8,
+ color = "#BDBDC3",
+ weight = 1,
+ popup = my_popup)
> mm