sf
This practical introduces spatial data handling and mapping in R, followed by a series of movement-ecology tasks using animal tracking data. You will work with world boundaries, GPS locations, time stamps, movement distances, kernel utilisation distributions, and biodiversity occurrence records.
The practical is designed to be completed step by step. Read the explanation before running each code chunk, inspect the output, and discuss questions with your demonstrator where indicated.
By the end of the practical, you should be able to:
sf
objects;Make sure the practical data files are available on your computer. The original script refers to:
Humpback_whale_ID112699.csvfalsekillerwhale.csvThe original script expects these files to be inside a folder named
OSX-3023_RPractical. Either keep that folder structure or
change the file paths in the read_csv() and
read.csv() commands below.
You only need to install a package once on a computer. If a package
is already installed, you do not need to install it again. Remove the
comment symbol # from an installation line when you need to
run it.
install.packages("cowplot")
install.packages("ggplot2")
install.packages("ggrepel")
install.packages("ggspatial")
install.packages("sf")
install.packages("rnaturalearth")
install.packages("rnaturalearthdata")
install.packages("terra")
install.packages("argosfilter")
install.packages("adehabitatHR")
install.packages("EMbC")
install.packages("geosphere")
install.packages("trip")
install.packages("readr")
install.packages("lubridate")
install.packages("tidyverse")
install.packages("ggpattern")
install.packages("rgbif")
Some spatial packages may require additional system libraries, depending on your operating system. If installation fails, note the full error message and ask your demonstrator for help.
library(cowplot)
library(ggplot2)
library(ggrepel)
library(ggspatial)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(terra)
library(argosfilter)
library(adehabitatHR)
library(EMbC)
library(geosphere)
library(trip)
library(readr)
library(lubridate)
library(tidyverse)
library(ggpattern)
For the biodiversity-download section later in the practical, you will also need:
library(rgbif)
sfsf object?The sf package provides a standard way to store and work
with vector spatial data in R. An sf object is similar to a
data frame, but it also contains a geometry column describing spatial
features such as points, lines and polygons. For example, a world
countries dataset contains country attributes and a polygon geometry for
each country.
Set a consistent plotting theme and download country boundaries from Natural Earth:
theme_set(theme_bw())
world <- ne_countries(
scale = "medium",
returnclass = "sf"
)
class(world)
## [1] "sf" "data.frame"
Explore: What class names are returned? Which column contains the geometries?
geom_sf() is designed to draw geometries stored in
sf objects.
myMap <- ggplot() +
geom_sf(data = world)
myMap
Try changing the fill and boundary colours. What happens if you map a
country attribute, such as continent, to
fill?
ggplot() +
geom_sf(data = world,aes(fill = continent),colour = "grey40",linewidth = 0.2) +
labs(title = "Countries of the world",fill = "Continent") +
theme_minimal()
A Coordinate Reference System (CRS) describes how spatial coordinates relate to locations on the Earth. Geographic CRSs commonly use longitude and latitude in angular units. Projected CRSs transform locations onto a flat map and commonly use linear units such as metres.
Inspect the CRS of the world dataset:
st_crs(world)
## Coordinate Reference System:
## User input: WGS 84
## wkt:
## GEOGCRS["WGS 84",
## DATUM["World Geodetic System 1984",
## ELLIPSOID["WGS 84",6378137,298.257223563,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["latitude",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["longitude",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",4326]]
The Robinson projection is a compromise world projection often used for general-purpose world maps. It does not preserve every property (area, distance, direction and shape) everywhere.
st_transform() changes the coordinates from the existing
CRS to the requested CRS.
world_robinson <- st_transform(world,crs = "+proj=robin +datum=WGS84")
ggplot() +
geom_sf(data = world_robinson) +
labs(title = "World map: Robinson projection") +
theme_minimal()
A projection’s central meridian controls which longitude is placed at the centre of the map. The following workflow breaks geometries at the antimeridian before transforming them. This helps avoid long, unwanted polygon edges when the map is centred away from the Greenwich meridian.
# Define a Robinson projection centred at 90 degrees East
robinson <- paste(
"+proj=robin +lon_0=90 +x_0=0 +y_0=0",
"+ellps=WGS84 +datum=WGS84 +units=m +no_defs"
)
# Break geometries at the antimeridian, then transform
world_robinson_indian <- world %>%
st_break_antimeridian(lon_0 = 90) %>%
st_transform(crs = robinson)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
# Approximate scale-bar position and length in projected metres
x_start <- -12000000
y_start <- -4000000
scale_length <- 2000000
ggplot() +
geom_sf(data = world_robinson_indian,aes(fill = continent),colour = "grey30",linewidth = 0.2) +
geom_segment(aes(x = x_start,xend = x_start + scale_length,y = y_start,yend = y_start),colour = "black",linewidth = 1) +
geom_text(aes(x = x_start + scale_length / 2,y = y_start - 1000000),label = "2000 km",size = 5) +
scale_fill_viridis_d() +
labs(
title = "World map",
subtitle = "Robinson projection centred on the Indian Ocean",
fill = "Continent"
) +
coord_sf(crs = st_crs(world_robinson_indian)) +
theme_minimal(base_size = 14) +
theme(
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()
)
The scale-bar coordinates above are manually positioned and are intended as a plotting exercise. For a publication-quality map, use a projection-aware scale-bar function and check that the scale is appropriate for the map location.
Try it: Change lon_0 = 90 to another
longitude. How does the map change? Try a central meridian near the
Atlantic or Pacific.
Key distinction:
st_transform()transforms coordinates.st_set_crs()assigns CRS metadata to coordinates that are already known to use that CRS; it does not transform the coordinates. Do not usest_set_crs()as a substitute for reprojection.
The North Polar Stereographic projection is useful for mapping high northern latitudes. Here we use EPSG:3413.
arctic <- st_transform(world, crs = 3413)
ggplot() +
geom_sf(data = arctic,fill = "lightblue",colour = "grey40",linewidth = 0.2) +
coord_sf(
xlim = c(-3000000, 3000000),
ylim = c(-3000000, 3000000),
crs = st_crs(3413)
) +
labs(
title = "The Arctic",
subtitle = "North Polar Stereographic projection (EPSG:3413)"
) +
theme_minimal()
For Antarctica, use the Antarctic Polar Stereographic projection, EPSG:3031.
antarctica <- st_transform(world, crs = 3031)
ggplot() +
geom_sf(data = antarctica,fill = "lightblue",colour = "grey40",linewidth = 0.2) +
coord_sf(
xlim = c(-3000000, 3000000),
ylim = c(-3000000, 3000000),
crs = st_crs(3031)
) +
labs(
title = "Antarctica",
subtitle = "South Polar Stereographic projection (EPSG:3031)"
) +
theme_minimal()
The world country-boundary layer is useful for demonstrating the projection, but a dedicated coastline or Antarctic continent dataset will show the Antarctic coastline in more detail.
lon_0 parameter control in the Robinson
projection?#Humpback whale: preparing and mapping tracking data ## Load the tracking data
Read the humpback whale dataset. Change the path if your file is stored somewhere else.
Humpback_whale_ID112699 <- read_csv("Humpback_whale_ID112699.csv")
Start by inspecting the data. Look at the first few rows and the structure of the columns.
Pause and inspect: Which columns contain the date, time, longitude and latitude? Are the coordinates stored as numeric values? Are there any missing values?
The date and time are initially stored in separate columns. Combine them into one character column:
Humpback_whale_ID112699$Date_Time <- paste(Humpback_whale_ID112699$Date,Humpback_whale_ID112699$Time,sep = " ")
Convert the combined date-time string into a POSIXct date-time object. The format string below assumes dates are written as day/month/year and times include hours, minutes and seconds.
Humpback_whale_ID112699$Date_TimePosix <- as.POSIXct(
Humpback_whale_ID112699$Date_Time,
format = "%d/%m/%Y %H:%M:%S"
)
class(Humpback_whale_ID112699$Date_Time)
## [1] "character"
class(Humpback_whale_ID112699$Date_TimePosix)
## [1] "POSIXct" "POSIXt"
If the conversion is unsuccessful, check the original date and time
strings. The format supplied to as.POSIXct() must match the
format in the data.
First, identify rows that contain at least one missing value:
Humpback_whale_ID112699 %>%
filter(if_any(everything(), is.na))
Now focus on rows where the converted date-time is missing:
Humpback_whale_ID112699[
which(is.na(Humpback_whale_ID112699$Date_TimePosix)),
]
The which() function returns the row positions where the
condition is true. Inspect the surrounding rows:
Humpback_whale_ID112699[1150:1160, ]
Discuss with your demonstrator what may have caused the problem. Do not invent dates or times. The practical removes rows where the date-time conversion failed:
Humpback_whale_ID112699 <- Humpback_whale_ID112699 %>%
filter(!is.na(Date_TimePosix))
Important: Removing records changes the track and may create a larger time gap between consecutive locations. Always document how many records were removed and consider how this affects later movement calculations.
Extract the month from the converted date-time:
Humpback_whale_ID112699$month_Date <- month(
Humpback_whale_ID112699$Date_TimePosix
)
Convert the month to a factor so it is treated as a category when mapping:
Humpback_whale_ID112699$month_Date <- as.factor(
Humpback_whale_ID112699$month_Date
)
Other examples of variables that might be treated as factors include season, sex, species and individual ID.
Start with a simple map showing the world and the whale’s locations.
myMap <- ggplot() +
geom_sf(data = world) +
geom_point(data = Humpback_whale_ID112699,mapping = aes(x = Longitude, y = Latitude))
myMap
The original practical focuses on the Southern Ocean region. Zoom in on the track and label the axes:
ggplot() +
geom_sf(data = world) +
geom_point(data = Humpback_whale_ID112699,aes(x = Longitude, y = Latitude)
) +
coord_sf(
xlim = c(-90, 0),
ylim = c(-90, 0)
) +
xlab(expression(paste("Longitude (", degree, "W)"))) +
ylab(expression(paste("Latitude (", degree, "S)")))
Improve the map by adding a scale bar and north arrow:
ggplot() +
geom_sf(data = world) +
geom_point(data = Humpback_whale_ID112699,aes(x = Longitude, y = Latitude)) +
coord_sf(
xlim = c(-85, 0),
ylim = c(-85, 0)
) +
xlab(expression(paste("Longitude (", degree, "W)"))) +
ylab(expression(paste("Latitude (", degree, "S)"))) +
ggspatial::annotation_scale(
location = "tr",
bar_cols = c("grey60", "white")
) +
ggspatial::annotation_north_arrow(
location = "tr",
which_north = "true",
pad_x = unit(0.4, "in"),
pad_y = unit(0.4, "in"),
style = ggspatial::north_arrow_nautical(
fill = c("grey40", "white"),
line_col = "grey20"
)
) +
theme_minimal()
The scale bar and north arrow are added by ggspatial.
Their position can be changed using arguments such as
location, pad_x and pad_y.
How many unique dates are there? How many unique months?
length(unique(Humpback_whale_ID112699$Date_Time))
## [1] 3219
length(unique(Humpback_whale_ID112699$month_Date))
## [1] 8
Colour the locations by month:
ggplot() +
geom_sf(data = world) +
geom_point(data = Humpback_whale_ID112699,aes(x = Longitude,y = Latitude,colour = month_Date),alpha = 0.7) +
coord_sf(
xlim = c(-85, 0),
ylim = c(-85, 0)
) +
xlab(expression(paste("Longitude (", degree, "W)"))) +
ylab(expression(paste("Latitude (", degree, "S)"))) +
ggspatial::annotation_scale(location = "tr") +
ggspatial::annotation_north_arrow(
location = "tr",
which_north = "true"
) +
labs(
title = "Humpback whale track",
colour = "Month"
) +
theme_minimal()
Try it: Improve the legend and experiment with colour palettes. Does the map make the seasonal progression of the track easier to interpret?
The original practical uses approximate coordinates for Brabant Island. Check these coordinates against an appropriate geographic source before treating them as definitive.
BI_LAT <- -64.3
BI_LON <- -62.3
brabant <- c(BI_LON, BI_LAT)
dist_from_island <- data.frame(
distGeo(
brabant,
Humpback_whale_ID112699[, c("Longitude", "Latitude")]
)
)
head(dist_from_island)
max(dist_from_island)
## [1] 7104303
distGeo() calculates geodesic distance between
longitude/latitude coordinates. Check the function documentation to
confirm the units returned.
Question: What is the maximum distance, and what are its units? Which whale location is furthest from the island?
The maximum straight-line distance from a reference point is not the same as the total distance travelled. To estimate track length, calculate the distance between each pair of consecutive locations and sum those distances.
First, create an object containing only longitude and latitude:
locs <- cbind(
Humpback_whale_ID112699$Longitude,
Humpback_whale_ID112699$Latitude
)
Calculate distances between consecutive locations:
locs <- data.frame(
trackDistance(locs, longlat = TRUE)
)
head(locs)
str(locs)
## 'data.frame': 4203 obs. of 1 variable:
## $ trackDistance.locs..longlat...TRUE.: num 3.72 0.576 1.173 2.708 1.231 ...
colnames(locs)[1] <- "dist"
head(locs)
Sum the distances:
sum(locs$dist, na.rm = TRUE)
## [1] 19546.22
Check the units returned by trackDistance() and report
the total track length with units.
Interpretation: This calculation joins consecutive recorded locations with straight segments. It estimates the distance along the observed track; it does not reveal the exact path the whale took between fixes.
A kernel utilisation distribution (KUD) estimates the intensity of an animal’s space use from its recorded locations. Contours such as 50% and 95% are commonly used to describe areas of concentrated use and broader space use. These contours are estimates and depend on the data and smoothing choices.
The adehabitatHR workflow used in the original practical
relies on spatial objects from the sp package and a
projected coordinate system.
hw.HR <- SpatialPointsDataFrame(
coords = cbind(
Humpback_whale_ID112699$Longitude,
Humpback_whale_ID112699$Latitude
),
data = Humpback_whale_ID112699,
proj4string = CRS(
"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
)
)
Transform the points to UTM Zone 18 South, as in the original practical:
hw.HR <- spTransform(
hw.HR,
CRS("+proj=utm +zone=18 +south +datum=WGS84 +units=m +no_defs")
)
Important: A suitable projected CRS is essential for home-range analysis because the calculations use distances and areas. Check that the chosen UTM zone is appropriate for the geographic extent of the track.
hw.HR <- kernelUD(hw.HR, h = "href")
## Warning in kernelUD(hw.HR, h = "href"): xy should contain only one column (the id of the animals)
## id ignored
Extract the 95% and 50% contours. The original script labels the 95%
contour as hbw.kud.95 and the 50% contour as
hbw.kud.50.
hbw.kud.95 <- getverticeshr(
hw.HR,
95,
unout = "km2"
)
hbw.kud.50 <- getverticeshr(
hw.HR,
50,
unout = "km2"
)
hbw.kud.95
## Object of class "SpatialPolygonsDataFrame" (package sp):
##
## Number of SpatialPolygons: 1
##
## Variables measured:
## id area
## homerange homerange 2710305
hbw.kud.50
## Object of class "SpatialPolygonsDataFrame" (package sp):
##
## Number of SpatialPolygons: 1
##
## Variables measured:
## id area
## homerange homerange 154051.9
Plot the contours:
plot(hbw.kud.95, col = "darkgrey")
plot(hbw.kud.50, col = "lightgrey", add = TRUE)
axis(1)
axis(2)
The 50% contour represents a smaller, more intensively used part of the estimated utilisation distribution than the 95% contour.
sf and add them to a mapConvert each contour to sf, transform it to
longitude/latitude, and add an identifying column:
hbw.kud.50_sf <- st_as_sf(hbw.kud.50) %>%
st_transform(crs = "+proj=longlat +datum=WGS84") %>%
mutate(id = "HR 50")
hbw.kud.95_sf <- st_as_sf(hbw.kud.95) %>%
st_transform(crs = "+proj=longlat +datum=WGS84") %>%
mutate(id = "HR 95")
single_sf_HW <- bind_rows(
hbw.kud.95_sf,
hbw.kud.50_sf
)
Plot the locations and home-range contours together:
ggplot() +
geom_sf(data = world) +
geom_point(data = Humpback_whale_ID112699,aes(x = Longitude,y = Latitude,colour = as.factor(ID))) +
scale_colour_manual(name = "Animal ID",values = "deepskyblue4") +
geom_sf(data = single_sf_HW,aes(fill = id),alpha = 0.4) +
scale_fill_manual(name = "Kernel - HR",
values = c("HR 95" = "grey80", "HR 50" = "grey10")
) +
coord_sf(
xlim = c(-90, 0),
ylim = c(-85, 5)
) +
xlab(expression(paste("Longitude (", degree, "W)"))) +
ylab(expression(paste("Latitude (", degree, "N)"))) +
ggspatial::annotation_scale(location = "br") +
ggspatial::annotation_north_arrow(
location = "tr",
which_north = "true"
) +
theme_minimal()
#Biodiversity occurrence data: GBIF
Biodiversity occurrence databases provide records of where organisms have been observed or collected. In this section, you will retrieve humpback whale records and map their geographic distribution.
GBIF covers terrestrial, freshwater and marine biodiversity.
The occ_search() function searches the GBIF occurrence
database. Here, we request up to 10,000 records for humpback whale. This
is a cap for a manageable practical exercise, not necessarily a complete
representation of the species’ known distribution.
res <- occ_search(
scientificName = "Megaptera novaeangliae",
limit = 10000
)
# Explore the function and its arguments
?occ_search
Extract the occurrence data and remove records without coordinates:
humpback_gbif <- res$data %>%
filter(
!is.na(decimalLongitude),
!is.na(decimalLatitude)
)
nrow(humpback_gbif)
## [1] 10000
Create a world map and plot the occurrence records:
world <- ne_countries(
scale = "medium",
returnclass = "sf"
)
ggplot() +
geom_sf(data = world,fill = "grey90",colour = "grey60") +
geom_point(data = humpback_gbif,aes(x = decimalLongitude, y = decimalLatitude),colour = "red",size = 1,alpha = 0.5) +
labs(title = "Humpback whale occurrences (GBIF data)",x = "Longitude",y = "Latitude") +
theme_minimal()
Explore the records:
unique(humpback_gbif$publishingCountry)
## [1] "US" "MX" "AU" "CA" "GR" "GB" "CR" "NO" "NL" "AR" "TW"
unique(humpback_gbif$basisOfRecord)
## [1] "HUMAN_OBSERVATION"
#False killer whale: mapping and home range
fkw <- read.csv("falsekillerwhale.csv",header = TRUE,sep = ",")
head(fkw)
str(fkw)
## 'data.frame': 1049 obs. of 4 variables:
## $ datetime : chr "2013-05-16 05:26:52" "2013-05-16 07:26:52" "2013-05-16 09:26:52" "2013-05-16 11:26:52" ...
## $ Longitude: num -172 -172 -171 -171 -171 ...
## $ Latitude : num 25.6 25.7 25.8 25.8 25.8 ...
## $ lbl : chr "128881-PcNHI-2013-SPOT5" "128881-PcNHI-2013-SPOT5" "128881-PcNHI-2013-SPOT5" "128881-PcNHI-2013-SPOT5" ...
summary(fkw)
## datetime Longitude Latitude lbl
## Length :1049 Min. :-173.8 Min. :22.96 Length :1049
## N.unique :1049 1st Qu.:-171.4 1st Qu.:24.35 N.unique : 1
## N.blank : 0 Median :-167.1 Median :24.88 N.blank : 0
## Min.nchar: 19 Mean :-167.6 Mean :25.04 Min.nchar: 23
## Max.nchar: 19 3rd Qu.:-165.0 3rd Qu.:25.79 Max.nchar: 23
## Max. :-158.6 Max. :27.28
Adapt the code we developed on the Humpback whales and:
Transforms coordinates to UTM Zone 4 North, and estimates a kernel utilisation distribution.
fkw.HR <- SpatialPointsDataFrame(
coords = cbind(fkw$Longitude, fkw$Latitude),
data = fkw,
proj4string = CRS(
"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
)
)
fkw.HR <- spTransform(
fkw.HR,
CRS("+proj=utm +zone=4 +north +datum=WGS84 +units=m +no_defs")
)
The practical uses the EMbC package to classify movement using speed
and turning-angle information. The scatterplot groups locations into
combinations of relatively low and high values. In the labels,
L means low and H means high.
The interpretation of clusters should be checked against the movement data and ecological context; cluster numbers do not automatically mean a particular behaviour.
embc_fkw <- stbc(fkw, info = -1)
## [1] 0 -0.0000e+00 4 1049
## [1] ... Stable clustering
Plot the classification:
sctr(embc_fkw)
The original practical describes the combinations as:
LL: low speed and low turning angle;LH: low speed and high turning angle;HL: high speed and low turning angle;HH: high speed and high turning angle.Add the cluster labels to the tracking data:
fkw$behaviour <- embc_fkw@A
embc_fkw@R
## X1.min X2.min X1.max X2.max
## 1.LL 0.000000 0.0000000 2.379360 0.2473594
## 2.LH 0.000000 0.2473594 2.575075 3.1400938
## 3.HL 2.379360 0.0000000 3.950960 0.4440307
## 4.HH 2.575075 0.4440307 3.950960 3.1400938
The following labels reproduce the interpretation in the original practical. Treat these as hypotheses to evaluate, rather than universal definitions of behaviour.
fkw$behaviour[fkw$behaviour == "1"] <- "resting"
fkw$behaviour[fkw$behaviour == "2"] <- "foraging"
fkw$behaviour[fkw$behaviour == "3"] <- "travelling"
fkw$behaviour[fkw$behaviour == "4"] <- "foraging"
fkw$behaviour[fkw$behaviour == "5"] <- "unknown"
The original script divides the number of fixes in each behaviour by the total number of fixes:
table(fkw$behaviour) / nrow(fkw)
##
## foraging resting travelling unknown
## 0.4432793136 0.5233555767 0.0324118208 0.0009532888
This is a proportion of recorded locations, not necessarily a proportion of elapsed time. It is most directly interpretable as a time budget when sampling intervals are regular and records are not missing.
fkw$behavCol[fkw$behaviour == "resting"] <- "darkgoldenrod1"
fkw$behavCol[fkw$behaviour == "foraging"] <- "deepskyblue2"
fkw$behavCol[fkw$behaviour == "travelling"] <- "dimgrey"
plot(
fkw$Longitude,
fkw$Latitude,
type = "l",
xlab = "Longitude",
ylab = "Latitude"
)
points(
fkw$Longitude,
fkw$Latitude,
col = fkw$behavCol,
pch = 20,
cex = 0.9
)
## Tasks - can you prepare a map showing the
behavioural classification?
Think about it: Are the inferred behaviours plausible given the animal’s movement? What additional information would help validate the classifications?
Choose one of the animal tracks and produce a publication-style map. Include:
Use R’s help system to explore functions while working:
?geom_sf
?st_transform
?st_crs
?st_break_antimeridian
?occ_search
?occurrence
?distGeo
?trackDistance
?kernelUD
?getverticeshr
?stbc
Useful package websites:
End of practical. Save your R script and any maps or outputs you create. Keep a note of any data-cleaning decisions, projection choices and assumptions made during the analysis.