Geographic Visualisation of Ecological Data in R

Geographic Visualisation of Ecological Data in R

This short tutorial explains basic geographic data visualisation for ecologists. I assume a basic knowledge of R, however if you have never used R before you should be able to follow along and copy the below scripts.

If you do not currently have R installed you can download it here. I would also highly recommend downloading the free RStudio editor.

For an introduction to R, i suggest the excelent and free R for data science ebook by Hadley Wickham & Garrett Grolemund, as well as the interactive datacamp course free introduction to R

Plotting basic maps

Set up for analysis

The first step for our analysis to set our working directory, and install the required R packages to run the analysis

The packages we will install are:

  • tidyverse - This is a collection of handy packages for data manipulation, exploration and visualization
  • maptools - This package contains the base world map data we will use
  • devtools - This package will allow installation of packages that have not yet been released on CRAN, such as the below patchwork package, directly from github
  • patchwork - This package allows easily composition of multiplots
setwd("/Users/alexanderpiper/Dropbox/R/Geographic") ##Change this to the directory you wish to work in

#install packages from CRAN
install.packages(c("tidyverse","maptools","devtools", "gpclib"))

# install packages from github
devtools::install_github("thomasp85/patchwork")

After packages are downloaded and installed, we then load them into our workspace

library("tidyverse")
library("maptools")
library("devtools")
library("patchwork")

Plotting a basic world map

First step is to plot a basic world map. For this we will use the simple world map dataset contained within the maptools package

#Get the simple world map data
data(wrld_simpl)
wrld_simpl@data$id <- wrld_simpl@data$NAME
gpclibPermit() # Give permissions to maptools to use gpclib
## [1] TRUE
wrld <- fortify(wrld_simpl, region="id")

# Plot simple worldmap with ggplot
wrld_plot <- ggplot() + geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat)) + coord_equal() 

#plot the map
plot(wrld_plot)

Changing the base map colours

Now we make some small changes to the base map colours and background to make it more visible

wrld_plot <- ggplot() + geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="lightgrey", color="#7f7f7f", size=0.25) + 
  coord_equal() + 
  theme_bw() #changes the theme to basic black and white

#plot the map
plot(wrld_plot)