[Solved] Make a cumulative plot of events in R


A possible solution:

library(lubridate)

# example time data
time = c(
  "2015-10-05 15:44:41.986797", "2015-10-05 15:59:23.389583", "2015-10-05 16:59:44.99402",
  "2015-10-05 16:59:44.99402", "2015-10-05 16:59:44.99402", "2015-10-05 16:59:44.99402",
  "2015-10-05 17:59:59.594524", "2015-10-05 17:59:59.594524", "2015-10-05 18:00:05.555564"
)

# transform time strings to POSIXct objects for count
time <- ymd_hms(time)

# count by second
event <- data.frame(table(time))

# transform time factors to POSIXct objects for df
event$time <- ymd_hms(event$time)

# find start and end time for 15min sequence
start <- round(min(event$time), "mins")
if (min(event$time) < start) {
  minute(start) <- minute(start) - 1
}
while (minute(start) %% 15 != 0) {
  minute(start) <- minute(start) - 1
}

end <- round(max(event$time), "mins")
if (max(event$time) > end) {
  minute(end) <- minute(end) + 1
}
while (minute(end) %% 15 != 0) {
  minute(end) <- minute(end) + 1
}

# create sequence and result data.frame
ft.seq <- seq(start, end, "15 mins")

ft.event <- data.frame(
  start = ft.seq[1:(length(ft.seq)-1)],
  end = ft.seq[2:(length(ft.seq))],
  sum = 0
)

# ugly, nested loop to attribute values to 15min time slices
for (p1 in 1:nrow(ft.event)) {
  for (p2 in 1:nrow(event)) {
    if (event$time[p2] > ft.event$start[p1] && 
        event$time[p2] < ft.event$end[p1]) {
      ft.event$sum[p1] <- ft.event$sum[p1] + event$Freq[p2]
    }
  }
}

# cumsum
ft.event$cumsum <- cumsum(ft.event$sum)

# example plot
library(ggplot2)

ggplot(ft.event) +
  geom_line(aes(x = end, y = cumsum))

3

solved Make a cumulative plot of events in R