Geographical Analysis in R

Packages for creating spatial visualisations

#install.packages("ggplot2")
#install.packages ("leaflet")
#install.packages("jsonlite")
#install.packages("maptools")
#install.packages("classInt")
#install.packages("RColorBrewer")


#leaflet is a dependency of tmap, so you will already have it, but it is cool on its own

Download the following files:

Download all the files at this link and add them to your working directory. For shapefiles to render correctly - even though you only load in the .shp file - the others need to be there in the background. The data is contained within the dataframe element of the ‘SpatialPolygonsDataFrame’.

You will need to create a user account but this is very straightforward.

Your first shapefile

library(maptools)
## Loading required package: sp
## Checking rgeos availability: TRUE
# Use the whole filepath not just the extension from your working directory

Man_LSOA <- readShapePoly("~/Dropbox/R_ladies/E08000003_IMD/E08000003.shp") #Polygons layer
## Warning: use rgdal::readOGR or sf::st_read
Man_Roads <- readShapeLines("~/Dropbox/R_ladies/E08000003_IMD/Road.shp") #Roads layer
## Warning: use rgdal::readOGR or sf::st_read
#Ignore the 'use rgdal::readOGR' message - you can look into this another time. It is a better package, but can be very stubborn! 
plot (Man_LSOA)

Adding data

library(classInt) #Load package
head(Man_LSOA@data)
##    LSOA11CD imd_rank imd_score income employment education health crime
## 0 E01005061      750     62.10   0.46       0.29     51.43   1.89  0.29
## 1 E01005062     7144     32.44   0.15       0.09     19.89   1.54  0.25
## 2 E01005063     1017     59.00   0.43       0.28     35.53   1.99  0.72
## 3 E01005065      892     60.46   0.40       0.29     35.43   2.05  1.01
## 4 E01005066     7253     32.18   0.16       0.13     13.11   1.36  0.73
## 5 E01005067       77     76.75   0.44       0.34     79.81   2.38  1.84
##   housing living_env idaci idaopi
## 0   40.64      13.02  0.55   0.67
## 1   49.19      30.04  0.26   0.63
## 2   34.45      25.42  0.50   0.56
## 3   32.23      33.24  0.43   0.58
## 4   40.16      31.73  0.29   0.57
## 5   33.87      22.49  0.52   0.51
#Replace imd_rank with any of the headings to plot the variable you are interested in.


breaks <- classIntervals(Man_LSOA@data$imd_rank, n = 5, style = "fisher") #Create 'fisher' breaks
library(RColorBrewer) #Load package

Color Brewer

#Select your colour palette - follow the link for lots of options and a great website for choosing map colour schemes

my_colours <- brewer.pal(6, "YlOrRd") 
my_colours
## [1] "#FFFFB2" "#FED976" "#FEB24C" "#FD8D3C" "#F03B20" "#BD0026"

We can then use the function findColours() to select the appropriate color for each of the numbers we intend to map, depending on where these fit within the break points we calculated.

colours_to_map <- findColours(breaks, my_colours)

We can then create a basic map using this list of colors and the plot() function again.

plot(Man_LSOA,col=colours_to_map,border = NA)

We can also add additional layers onto the map using a further parameter (“add”) which is set to “TRUE”. Without the “add=TRUE”, every time plot() is called, the previous plot is replaced. Two further parameters are used, “col” to specify the line color, and “lwd” the line width.

plot(Man_LSOA,col=colours_to_map,border = NA)
plot(Man_Roads,add=TRUE, col="#252525", lwd=0.1)

Another feature that is very common to see on a map is a legend which tells you what values the colors used on the map correspond to. This combines the legend() function with a further function leglabs() (from the maptools package) to create a legend:

# Plot choropleth - run whole code block together!
plot(Man_LSOA,col=colours_to_map,border = NA)
# Plot roads
plot(Man_Roads,add=TRUE, col="#252525",lwd=0.1)
# Add legend
legend("bottomleft" ,legend = leglabs(breaks$brks, between = " to "), fill = my_colours, bty = "n",cex=0.6)

Fancy interactive stuff

library(leaflet)

mymap <- leaflet(height = 300) %>%
  addTiles() %>%
  setView(lng = -2.236145, lat = 53.482215, zoom = 16)

mymap
mymap <- mymap %>% 
  addMarkers(-2.236145, 53.482215, popup="Hello R-Ladies!") # add a marker

mymap

Fancy interactive stuff with data!

Go to the following link

Copy and paste your own signed URL!

library(jsonlite)

meet_up <- as.data.frame(fromJSON("https://api.meetup.com/recommended/groups?photo-host=public&location=Manchester&zip=M15+6JJ&page=20&country=gb&sig_id=107413022&omit=description&sig=c9a1c2f8b776217244b51facb39353930e63ffd8")) #Replace this signed URL with your own!

Check that your lat and long are actually in columns 15 and 16!

names(meet_up) [15] <- c("Lat") #rename colums
names(meet_up) [16]<- c("Lon") #rename colums
#Create a spatial dataframe using the lat and long values from 'meet_up'
coords <- cbind(meet_up$Lon, meet_up$Lat)
sp <- SpatialPoints(coords) # Turn these coords into points
spdf <- SpatialPointsDataFrame(coords, meet_up) #Rejoin these points to the original data
#Try zooming out on the map if you don't get any markers immediately!
mymeets <- mymap %>% 
  addMarkers(data=spdf, popup= spdf$name, clusterOptions = markerClusterOptions()) # add markers and cluster

mymeets

Some online web mapping

Create nice and easily shareable visualisations by just uploading data with a spatial element; points, postcodes, polygons, lines etc.

Websites for more information and tutorials

My supervisors both produce great open resources for spatial analysis in R (and python)

Any other business

CDRC maps

Today’s data is openly available by creating a user account at CDRC data