[R] Plot a path
Jan van der Laan
rhe|p @end|ng |rom eoo@@dd@@n|
Thu Nov 1 14:38:52 CET 2018
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:
> 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:
>>
>> Dear All,
>> I have a dataframe with four cols: Date, Placename, geogr. latitude,
>> geogr. longitude.
>> How can I plot the path as a line, ordered by the date, with the
>> longitude as the x-axis and the latitude as the y-axis?
>> Thank you in advance!
>> Yours, Ferri
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list