Skip to content

Plot a path

2 messages · Rui Barradas, Jan van der Laan

#
Hello,

The following uses ggplot2.

First, make up a dataset, since you have not posted one.



lat0 <- 38.736946
lon0 <- -9.142685
n <- 10

set.seed(1)
Date <- seq(Sys.Date() - n + 1, Sys.Date(), by = "days")
Lat <- lat0 + cumsum(c(0, runif(n - 1)))
Lon <- lon0 + cumsum(c(0, runif(n - 1)))
Placename <- rep(c("A", "B"), n/2)

path <- data.frame(Date, Placename, Lat, Lon)
path <- path[order(path$Date), ]


Now, two graphs, one with just one line of all the lon/lat and the other 
with a line for each Placename.

library(ggplot2)

ggplot(path, aes(x = Lon, y = Lat)) +
   geom_point() +
   geom_line()


ggplot(path, aes(x = Lon, y = Lat, colour = Placename)) +
   geom_point(aes(fill = Placename)) +
   geom_line()


Hope this helps,

Rui Barradas

?s 21:27 de 31/10/2018, Ferri Leberl escreveu:
#
Below a similar example, using sf and leaflet; plotting the trajectory 
on a background map.


library(leaflet)
library(sf)
library(dplyr)

# Generate example data
gen_data <- function(id, n) {
   data.frame(
     id = id,
     date = 1:n,
     lat = runif(10, min = -90, max = 90),
     lon = runif(10, min = -180, max = 180)
   )
}

dta <- lapply(1:2, gen_data, n = 10) %>% bind_rows()

# Transform all records of one object/person to a st_linestring, then
# combine into one sf column
lines <- dta %>%
   arrange(id, date) %>%
   split(dta$id) %>%
   lapply(function(d) st_linestring(cbind(d$lon, d$lat))) %>%
   unname() %>%   # Without the unname it doesn't work for some reason
   st_sfc()

# Plot using leaflet
leaflet() %>%
   addTiles() %>%
   addPolylines(data = lines)


HTH - Jan
On 01-11-18 11:27, Rui Barradas wrote: