Polygon plotting in R

[This article was first published on Rbloggers – The Analytics Lab, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

 
As a data analyst you want to provide clear cut insights for your end users, enabling them to extract all the business value provided by your solution. If your end user is data and analytical savvy then explaining results might be a piece of cake. Unfortunately not all stakeholders are able to fully grab the potential of your solution. In that scenario data visualisation is a powerful concept. Data visualisation enables you to provide the core insights in a single graphic. In this video we demonstrate how to easily visualize data with a geographical component in R using leaflet. (the code can be found below the video)
In this example we use open source government data: data on characteristics of inhabitants and a GeoJSON datafile. GeoJSON is a popular data format for many geographical technologies and services mainly because it’s simple, lightweight and straightforward. We use the leaflet package in R because it handles GeoJSON data very well straight out of the box.
# --------------------------------------------------------------- #
# What    :   Plot neighborhood data on geo-map (city of Utrecht) #
# Author  :   Wouter van Gils ([email protected])              #
# Date    :   February 2019                                       #
# --------------------------------------------------------------- #

# packages required
library(geojsonio)
library(leaflet)
library(magrittr)
library(htmlwidgets)



#######################
## READ POLYGON DATA ##
#######################

# Read shapefile: Spatial Polygon DB
neighborhoods_utrecht <- geojson_read("neighborhoods-utrecht.geojson", method= "local", what = "sp")

# What kind of data does this spatial object contain
head(neighborhoods_utrecht@data)

# Show the neighborhoods of Utrecht on a Leaflet map
leaflet(neighborhoods_utrecht) %>%
  #addProviderTiles("nlmaps.standaard") %>% 
  addProviderTiles("Esri.WorldGrayCanvas") %>%
  addPolygons(stroke = TRUE, color = "white", weight="1", smoothFactor = 0.3, fillOpacity = 0.7, fillColor = "lightblue")



##################################
## LOAD DATA TO PLOT ON POLYGON ##
##################################

# Import data to be displayed on the map 
utrecht_data <- read.csv("data_utrecht.csv", header = TRUE, sep = ";", quote = "\"", dec = ".", fill = TRUE)

# Create merge ID and merge data
neighborhoods_utrecht@data$gwb_buurt_code <- 344 * 10000 + as.numeric(levels(neighborhoods_utrecht@data$KODE))[neighborhoods_utrecht@data$KODE] 
neighborhoods_utrecht@data <- merge(neighborhoods_utrecht@data, utrecht_data, by.x="gwb_buurt_code", by.y="gwb_buurt_code")



#########################
## DISPLAY DATA ON MAP ##
#########################

# Define cut points for the colorbins
cuts <- c(0.0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30, 1)

# Choose a color palette and assign it to the values
colorbins <- colorBin("YlOrRd", domain = neighborhoods_utrecht$p_65_inf, bins = cuts)

# Display data on elderly people on the map 
map <-  leaflet(neighborhoods_utrecht) %>%
                addTiles() %>%
                addProviderTiles("Esri.WorldGrayCanvas") %>%
                addPolygons(stroke = TRUE, color = "white", weight="1", smoothFactor = 0.3, 
                            fillOpacity = 0.7, fillColor = ~colorbins(neighborhoods_utrecht$p_65_inf))  

map

# Add a legend
map_with_legend <- map %>% addLegend(pal = colorbins, 
                                      values = neighborhoods_utrecht$p_65_inf,
                                      labFormat = labelFormat(suffix = " %", transform = function(p_65_inf) 100 * p_65_inf),
                                      opacity = 0.7, title = "Residents of age 65 and older", position = "topright")

map_with_legend



###########################################
## ADD MOUSE-OVER HIGHLIGHTS AND TOOLTIP ##
###########################################

# Create HTML labels for tooltip
tooltip <- sprintf("<strong>%s</strong><br/>%.1f%% elderly residents"
                   ,neighborhoods_utrecht$gwb_buurt_naam
                   ,neighborhoods_utrecht$p_65_inf*100
                  ) %>% lapply(htmltools::HTML)


# Display map
map_with_tooltip <- map_with_legend %>% addPolygons(stroke = TRUE, color = "white", weight="1", smoothFactor = 0.3, fillOpacity = 0.7, 
                                        fillColor = ~colorbins(neighborhoods_utrecht$p_65_inf), 
                                        highlight = highlightOptions(weight = 5, color = "grey", fillOpacity = 0.7, bringToFront = TRUE),
                                        label = tooltip
                                                   )
map_with_tooltip



###########################
## SAVE OUTPUT HTML FILE ##
###########################

# Save output as HTML widget (or incorporate into Shiny / Flexdashboard)
saveWidget(map_with_tooltip, file="Elderly residents in Utrecht.html")
The end result is a portable HTML file you can use in reports, on a webpage or in a R dashboard (flexdashboard / shiny). This video covers the basics of visualising geographical data in R with leaflet. There are many options that can be added quite easily. The R-script and data files can be found on GitHub.
A short note on data security: the output of the leaflet package is a standalone html-file, so no information is send to a web server. To be completely safe, only add data to the GeoJSON data matrix that you are willing to share with the public you provide access to the output file.
 

this article is written by

Wouter van Gils [email protected]

To leave a comment for the author, please follow the link and comment on their blog: Rbloggers – The Analytics Lab.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)