library(leaflet)
Assume we have a data on Tunisia at the Gouvernorat level: The Regional Development Index at the gouvernorat level:
library(readr)
idr_gouv <- read_csv("idr_gouv.csv")
head(idr_gouv)
## # A tibble: 6 x 3
## HASC_1 gouvernorat IDR
## <chr> <chr> <dbl>
## 1 TN.TU TUNIS 0.76
## 2 TN.AN ARIANA 0.69
## 3 TN.BA BEN AROUS 0.66
## 4 TN.MS MONASTIR 0.64
## 5 TN.SS SOUSSE 0.62
## 6 TN.NB NABEUL 0.570
Note that the data should a column with HASC_1 codes
library(raster)
tnMAP<- getData(name="GADM",
country="TUN", level=1)
tnMAP
## class : SpatialPolygonsDataFrame
## features : 24
## extent : 7.530076, 11.59826, 30.23681, 37.55986 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## variables : 13
## names : OBJECTID, ID_0, ISO, NAME_0, ID_1, NAME_1, HASC_1, CCN_1, CCA_1, TYPE_1, ENGTYPE_1, NL_NAME_1, VARNAME_1
## min values : 1, 234, TUN, Tunisia, 1, Ariana, TN.AN, NA, , Wilayat, Governorate, ,
## max values : 24, 234, TUN, Tunisia, 24, Zaghouan, TN.ZA, NA, , Wilayat, Governorate, , Tunis South|Zachouan|Zaguan|Zaghwān|Saghuan
Transforming them all lower cases and using match command
i=match(tnMAP$HASC_1,idr_gouv$HASC_1)
i
## [1] 2 18 3 14 10 16 21 23 24 12 17 13 15 9 4 6 7 22 20 5 8 11 1
## [24] 19
Merging then the data
tnMAP=cbind.Spatial(tnMAP,idr_gouv[i,])
col<-colorRampPalette(c("gray","firebrick4"))
e<-col(24)
pal<-colorNumeric(e,domain=tnMAP@data$IDR,n=24)
leaflet(tnMAP) %>%addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = .8,
opacity = 1,dashArray = "3",
fillColor = ~pal(IDR),
highlight = highlightOptions(
weight = 5,
color = "black",
bringToFront = TRUE))
labels<-sprintf("<strong>%s</strong><br/>%g",tnMAP@data$NAME_1,tnMAP@data$IDR)
labels<-labels%>%lapply(htmltools::HTML)
m<-leaflet(tnMAP) %>%addProviderTiles(providers$CartoDB.Positron)%>%addPolygons(fillColor=~pal(IDR),group="IDR",fillOpacity=10,col="black",weight=1.1,opacity=0.7,highlight=highlightOptions(weight=4.0,color="#FFFFFF",fillOpacity = 0.7,bringToFront = TRUE),label=labels,labelOptions=labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto"))
m
m<-m%>% addLegend(pal=pal,values=~IDR,opacity=1.5,position="bottomright",title = "RDI")
m
rr<-"Regional Development Index (2012)"
m<-m%>% addControl(rr, position = "bottomleft")
m