library(dplyr)
## Warning: package 'dplyr' was built under R version 3.5.1
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(forecast)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following object is masked from 'package:base':
## 
##     date
load("track_all.rdata")
 colnames(track_all)[1] <- "Name"
meta <- read.csv("EleMetaDat.csv", stringsAsFactors = F)
track_all <- left_join(track_all, meta[,1:2], by = c('Name'))
## Warning: Column `Name` joining factor and character vector, coercing into
## character vector
myele <- "Lisa"
start <- ymd_hms("2017-05-31 23:59:59")
end <- ymd_hms("2017-09-01 00:00:00")

track = track_all %>%
  select(name = Name, x=X, y=Y, timestamp=Fixtime, sex=Sex) %>%
  mutate_if(is.factor, as.character) %>%
  mutate(timestamp = ymd_hms(timestamp)) %>%
  filter(name == myele, timestamp > start, 
         timestamp < end) %>%
  group_by(name) %>%
  arrange(timestamp) %>%
  distinct()

res = list()
i=1

repeat {

  res[[i]] = track %>%
  transmute(
    time_diff = difftime(timestamp, lag(timestamp, i), units="mins"),
    x_diff = x - lag(x, i),
    y_diff = y - lag(y, i),
  ) %>% 
  na.omit()

  if (min(res[[i]]$time_diff) > 60*96 | i > 500)
    break
  
  i=i+1
}
nhours = 50
  
df = bind_rows(res) %>%
  filter(time_diff < 60*nhours) %>%
  mutate(hour = cut(as.numeric(time_diff)/60,breaks = seq(0,nhours,2)))

png("test.png", width = 2000, height = 2000)
ggplot(df, aes(x=x_diff,y=y_diff)) +
  stat_density_2d(geom = "polygon", aes(fill = stat(nlevel))) + 
  scale_fill_viridis_c() +
  facet_wrap(~hour)
dev.off()
## quartz_off_screen 
##                 2
knitr::include_graphics("test.png")