Home > OS >  How do I implement geom_path on a sf object containing GPS location data mapped using ggplot2
How do I implement geom_path on a sf object containing GPS location data mapped using ggplot2

Time:08-25

I need to create path trajectory using GPS location data collected at 15 minute intervals from an animal. The base map is created using a ggplot and the sf package. Here is the code and a snippet of the data.

# Libraries
library(tidyverse)
library(sf)
# GPS data
gps_6067 = data.frame(DT_UTC = as.POSIXct(c('2020-07-08 00:00:08', '2020-07-08 00:15:08', '2020-07-08 00:30:08', '2020-07-08 00:45:08', '2020-07-08 01:00:09', '2020-07-08 01:15:09', '2020-07-08 01:30:08', '2020-07-08 01:45:09', '2020-07-08 02:00:39', '2020-07-08 02:15:10'),  format = '%Y-%m-%d %H:%M:%S'),
                         Lat = c(44.21540, 44.21525, 44.21497, 44.21506, 44.21514, 44.21525, 44.21560, 44.21552, 44.21534, 44.21526),
                         Lon = c(-87.20221, -87.20262, -87.20264, -87.20298 ,-87.20318, -87.20343, -87.20360, -87.20365, -87.20353, -87.20391))

So now we have the data, I can make a ggplot showing the path connecting temporally sequential gps locations

ggplot(data = gps_6067, aes(x = Lon, y = Lat)) 
  geom_point() 
  geom_path()

Now, I need to plot this on top of a raster and other spatial data, which I am using the sf package for.

# Create an sf spatial object
gps_6067.sf = st_as_sf(gps_6067,
                       coords = c("Lon", "Lat"),
                       crs = crs(" proj=longlat  datum=WGS84  ellps=WGS84  towgs84=0,0,0"),
                       remove = F)
# So far so good, and it plots like it would be expected to
# Plot the points using ggplot
ggplot() 
  geom_sf(data = gps_6067.sf, size = 1.5, aes(color = DT_UTC)) 
  scale_color_datetime(low = 'orange', high = 'green')

This works, but I need to add a path layer to the new map

ggplot() 
  geom_sf(data = gps_6067.sf, size = 1.5, aes(color = DT_UTC)) 
  scale_color_datetime(low = 'orange', high = 'green') 
  geom_path(data = gps_6067.sf)

I know that I have to specify the crs to the geom_path command, but I haven't seen it implemented. Any insight is appreciated!!!!

CodePudding user response:

Try adding:

ggplot() 
  geom_sf(data = gps_6067.sf, size = 1.5, aes(color = DT_UTC)) 
  scale_color_datetime(low = 'orange', high = 'green') 
  geom_path(data = gps_6067.sf, aes(x = Lon, y = Lat))

This will connect the points and create the path.

I believe you mentioned something about a raster? Do you have sample code for that?

CodePudding user response:

Generally, to add a raster layer to a plot I would convert it to data.frame and use geom_tile.

example

library(dplyr)
library(terra)
r <- rast('path_to_raster.tif') %>% as.data.frame(xy=T)

# Check the name of column you want to use as color
names(r)

ggplot()  
  geom_tile(data = r, aes(x = x, y = y, fill = <colName>))  
  geom_sf(data = GPS etc...) # this part you already have
  • Related