Loading libraries

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggrepel)
library(tidyr)
library(gganimate)
library(stringr)

Reading in the data set

combined_data <- read_csv("DSADFinal_Data.csv") 
## Rows: 144 Columns: 19
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (13): caseNbr, lastName, firstName, Program, DOB, Gender, Race, docketN...
## dbl   (2): Age, lengthIncidentRef
## date  (4): dateIncident, dateRef, dateIntake, dateClsd
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Reshaping data
long_data <- combined_data |>
    subset(select = -dateDivClsd) |>
  pivot_longer(cols = starts_with("date"), 
               names_to = "phase", 
               values_to = "date") 


# Convert phase names
long_data$phase <- sub("date_of_", "", long_data$phase)

Creating offense categories

long_data <- long_data |> 
  mutate(date = as.Date(date)) |>
  mutate(
    offense = case_when(
      str_detect(offenseType, "DUI #2 - INFLUENCE|DUI #1 - INFLUENCE|DUI #1 - DRUG OR BOTH|DUI #1 - INFLUENCE, LEAVING SCENE OF CRASH - PROPERTY DAMAGE|VEHICLE OPERATION - LICENSE SUSPENDED  #1 FOR DUI|DUI #1 > LEGAL LIMIT|VEHICLE OPERATION - LICENSE SUSPENDED #2 FOR DUI") ~ "DUI and Related Offenses",
      
      str_detect(offenseType, "ASSAULT - SIMPLE|VIOLATION OF ABUSE PREVENTION ORDER|ASSAULT - SIMPLE, VIOLATION OF CONDITIONS OF RELEASE|AGGRAVATED ASSAULT ON A LAW ENFORCEMENT OFFICER - THREATEN WITH DEADLY WEAPON,  SIMPLE ASSAULT ON A PROTECTED PROFESSIONAL - BODILY INJURY") ~ "Assault and Abuse Violations",
      
       str_detect(offenseType, "RECKLESS ENDANGERMENT|VEHICLE OPERATION - RECKLESS OR GROSS NEGLIGENCE - #1|VEHICLE OPERATION - EXCESSIVE SPEED|VEHICLE OPERATION - CARELESS OR NEGLIGENT|LEAVING SCENE OF CRASH - PROPERTY DAMAGE") ~ "Reckless and Negligent Behavior",
      
       str_detect(offenseType, "UNLAWFUL TRESPASS - RESIDENCE/OCCUPIED|UNLAWFUL TRESPASS - LAND") ~ "Tresspassing",
       str_detect(offenseType, "DISORDERLY CONDUCT- FIGHT ETC") ~ "Disorderly Conduct",
      
       str_detect(offenseType, "VIOLATION OF CONDITIONS OF RELEASE|VEHICLE OPERATION - LICENSE SUSPENDED/OSC|VEHICLE OPERATION - LICENSE SUSPENDED") ~ "Violation of Legal Order",

            is.na(offenseType) | offenseType == "" ~ "Unknown", # Handles NA and empty strings
      TRUE ~ "Theft and Property-Related Crimes"  
    )
  )

Prepping data for the animation

# set of phases for each person
dfAnimate <- long_data |>
  complete(lastName, nesting(Program, offense), phase = c("dateIncident", "dateRef", "dateIntake", "dateClsd"))

# arrange by last name and date, then fill forward the dates within each group

dfAnimate <- dfAnimate |>
  filter(date >= "2023-01-01")|>
  arrange(lastName, date) |>
  group_by(lastName) |>
  fill(date, .direction = "down") |>
  ungroup()

dfAnimate$phase <- factor(dfAnimate$phase, levels = c("dateIncident", "dateRef", "dateIntake", "dateClsd"))

write_csv(dfAnimate, "dfAnimate.csv")

Create the plot

p <-
  ggplot(dfAnimate, aes(x = phase, y = Program, group = lastName, color = offense), alpha = 1) +
   labs(color = "Category of Offense") +
  geom_jitter(aes(size = !is.na(date))) +

  
  labs(title = 'Date: {frame_along}', x = 'Phase', y = 'Program Name') +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_color_brewer(palette = "Set1") +
  transition_states(states = phase, transition_length = 20, state_length = 10) +
  transition_time(date) +

  guides(size = 'none')  # Hide the size legend 


# create a data frame for the background bars

rect_data <- data.frame(
  xmin = -Inf, xmax = Inf,
  ymin = c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5), 
  ymax = c(1.5, 2.5, 3.5, 4.5, 5.5, 6.5),
  fill = c("white", "snow4", "white", "snow4", "white", "snow4")
    )

# save to directory
write_csv(rect_data, "rect_data.csv")

# Add rectangles
p <- p + geom_rect(data = rect_data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), alpha = 0.2, inherit.aes = FALSE) +
  scale_fill_identity()  # Use the colors defined in rect_data


# Create the animation
anim <- p + 
  transition_reveal(along = date) +
  ease_aes('linear') 

# Save the animation
anim_save("anim.gif", animation = anim, fps = 10)
## Warning: Using size for a discrete variable is not advised.
anim 
## Warning: Using size for a discrete variable is not advised.