tmap

r
sula
Y2024
biologging
gis

Create an interactive map to explore your data.

Author

Miriam Lerma

Published

December 4, 2024

Intro

When analyzing tracking data in R, you may want to explore the locations. One option is to export the cleaned data set and open it a GIS program. However, R also offers interactive mapping features. In this post, I’ll walk you through the steps I used to create interactive maps with my GPS data.

Data

For the exercises, test data is from masked boobies.
To access the data you have to install the package sula: devtools::install_github(“MiriamLL/sula”)

library(sula)
Data_1original<-GPS_preparado 

Transform

The function fortify helps the data frame to be more easily be plotted.

library(tidyverse)
Data_2fortify<-fortify(Data_1original)

Make sure your lat and lon are numerical

Data_2fortify$lat<-as.numeric(Data_2fortify$Latitude)
Data_2fortify$lon<-as.numeric(Data_2fortify$Longitude)

Transform to spatial.

library(sf)

Select which CRS you will like to use.

Data_3spatial <- st_as_sf(Data_2fortify, coords = c("lon", "lat"),crs = 4326, agr = "constant")

Select the columns that are of interest.

Data_4info<-Data_3spatial[,c("IDs","trip_number","dia_hora")]

Map

Install the package tmap.

This package allows you to create interactive maps.

library(tmap)

For making the map interactive, the mode view should be declared.

tmap_mode("view") 

To create your map with points you can use the arguments tm_shape and tm_dots

tm_shape(Data_4info)+
   tm_dots()

To rename the information that shows, you can add the argument popup.vars

tm_shape(Data_4info)+
   tm_dots(id = "IDs",col="yellow",popup.vars=c("trip_number"="trip_number","dt"="dia_hora"))

To separate between individuals you can also include them as separated layers.

tm_shape(subset(Data_4info,Data_4info$ID=='GPS01'))+
   tm_dots(id = "IDs",col="yellow",popup.vars=c("trip_number"="trip_number","dt"="dia_hora"))+
  tm_shape(subset(Data_4info,Data_4info$ID=='GPS03'))+
   tm_dots(id = "IDs",col="red",popup.vars=c("trip_number"="trip_number","dt"="dia_hora"))

Interact with you map

Using you can zoom-in to see the points.
Using you can zoom-out to see the points.

Using you can select which layers to show.

Put the cursor on top of the dot , when appears click on it and you should be able to see the ID, trip number and dt and time of the point.

tm_shape(subset(Data_4info,Data_4info$ID=='GPS01'))+
   tm_dots(id = "IDs",col="yellow",popup.vars=c("trip_number"="trip_number","dt"="dia_hora"))+
  tm_shape(subset(Data_4info,Data_4info$ID=='GPS03'))+
   tm_dots(id = "IDs",col="red",popup.vars=c("trip_number"="trip_number","dt"="dia_hora"))

Using tmap might save you the step to export your dataframe, and the import it into another program, particularly if you want to check a particular point and particular information associated to that point.

Further reading