Search code examples
rggplot2gganimate

Calculating the difference between values in a time series data frame using R


I have a data frame in R that contains two columns: Date_Time and Heat_Capacity. Each row represents a 1-second interval of data. Example:

start_date <- ymd_hms("2023-06-14 09:43:06")
end_date <- ymd_hms("2023-06-14 10:43:29")

df <- data.frame(
  Date_Time  =   seq(start_date, end_date, by = "1 sec"),
  Heat_Capacity = rep(c(
    3322.97,4215.97,4522.97,3822.97,1262.97,7462.87,336.12,3459.23
  ))
)
df$Date_Time <- as.POSIXct(df$Date_Time)

The code below results in showing each value in the column of 'Heat_Capacity' and it changes based on values in Date_Time Column

p1 <- ggplot(data = df) +
  theme_void() +
  geom_text(aes(label = paste0("Heat Capacity = ",Heat_Capacity), x = 0, y = 2.0)) +
  scale_y_continuous(limits = c(0, 2)) +
  transition_time(Date_Time)

animate(p1, fps = 24, renderer = gifski_renderer())

I'm trying to use like a 15min filter, so when render it shows a "value" = Heat capacity values at 15th minute - Heat Capacity value at 0th minute .

For example:
I want to display the result of these based on below equation

Heat Capacity value[09:58:06] - Heat Capacity value[09:43:06] 
Heat Capacity value[09:58:07] - Heat Capacity value[09:43:07]
Heat Capacity value[09:58:08] - Heat Capacity value[09:43:08]

Do I need to modify the whole data frame to get the result or can I do it inside the ggplot code


Solution

  • You can calculate the diff with lag() function, like:

    start_date <- lubridate::ymd_hms("2023-06-14 09:43:06")
    end_date <- lubridate::ymd_hms("2023-06-14 10:43:29")
    
    df <- data.frame(
      Date_Time  =   seq(start_date, end_date, by = "1 sec"),
      Heat_Capacity = rep(c(
        3322.97,4215.97,4522.97,3822.97,1262.97,7462.87,336.12,3459.23
      ))
    )
    
    df |>
      dplyr::mutate(diff = Heat_Capacity - dplyr::lag(Heat_Capacity, 15*60)) |>
      tail()
    
    #>                Date_Time Heat_Capacity     diff
    #> 3619 2023-06-14 10:43:24       4522.97  4186.85
    #> 3620 2023-06-14 10:43:25       3822.97   363.74
    #> 3621 2023-06-14 10:43:26       1262.97 -2060.00
    #> 3622 2023-06-14 10:43:27       7462.87  3246.90
    #> 3623 2023-06-14 10:43:28        336.12 -4186.85
    #> 3624 2023-06-14 10:43:29       3459.23  -363.74
    

    And then plot or animate it.

    Created on 2023-06-27 with reprex v2.0.2