• Steven Ponce
  • About
  • Data Visualizations
  • Projects
  • Resume
  • Email

On this page

  • Original
  • Makeover
  • Steps to Create this Graphic
    • 1. Load Packages & Setup
    • 2. Read in the Data
    • 3. Examine the Data
    • 4. Tidy Data
    • 5. Visualization Parameters
    • 6. Plot
    • 7. Save
    • 8. Session Info
    • 9. GitHub Repository
    • 10. References
    • 11. Custom Functions Documentation

Pet cats rest 70–80% of the day regardless of season

  • Show All Code
  • Hide All Code

  • View Source

Accelerometer data from 28 New Zealand cats shows most time is spent lying or sitting, with only small differences by season, housing, or household environment.

MakeoverMonday
Data Visualization
R Programming
2025
A Makeover Monday redesign exploring pet cat activity patterns using accelerometer data. The original icon-based scatter plot is transformed into a clean quadrant chart comparing seasonal resting behavior, paired with a dot plot examining environmental factors like children and dogs in the household.
Published

December 2, 2025

Original

The original visualization comes from Do cats really loaf all day?

Original visualization

Makeover

Figure 1: Two-panel chart examining cat resting behavior. Left panel: Scatter plot comparing 28 cats’ resting time in summer (x-axis) versus winter (y-axis), ranging from 55-90%. Points cluster along the diagonal ‘no change’ line, mostly within 70-80%, indicating minimal seasonal variation. Blue points represent indoor cats, orange points represent indoor & outdoor cats. Right panel: Dot plots showing resting time by household environment. Cats in homes with children rest slightly less (~70%) than those without (~75%), while dog presence shows minimal difference. Individual cats are shown as points with mean ± SE bars overlaid.

Steps to Create this Graphic

1. Load Packages & Setup

Show code
```{r}
#| label: load
#| warning: false
#| message: false
#| results: "hide"

## 1. LOAD PACKAGES & SETUP ----
suppressPackageStartupMessages({
  if (!require("pacman")) install.packages("pacman")
  pacman::p_load(
    tidyverse,     # Easily Install and Load the 'Tidyverse'
    janitor,       # Simple Tools for Examining and Cleaning Dirty Data
    skimr,         # Compact and Flexible Summaries of Data
    scales,        # Scale Functions for Visualization
    ggtext,        # Improved Text Rendering Support for 'ggplot2'
    showtext,      # Using Fonts More Easily in R Graphs
    glue,          # Interpreted String Literals
    patchwork      # The Composer of Plots
)
})

### |- figure size ----
camcorder::gg_record(
    dir    = here::here("temp_plots"),
    device = "png",
    width  = 10,
    height = 8,
    units  = "in",
    dpi    = 320
)

# Source utility functions
suppressMessages(source(here::here("R/utils/fonts.R")))
source(here::here("R/utils/social_icons.R"))
source(here::here("R/utils/image_utils.R"))
source(here::here("R/themes/base_theme.R"))
```

2. Read in the Data

Show code
```{r}
#| label: read
#| include: true
#| eval: true
#| warning: false
#|

cats_data <- read_csv(
  here::here("data/MakeoverMonday/2025/cats_data.csv")) |>
  clean_names()
```

3. Examine the Data

Show code
```{r}
#| label: examine
#| include: true
#| eval: true
#| results: 'hide'
#| warning: false

glimpse(cats_data)
skim(cats_data) |> summary()
```

4. Tidy Data

Show code
```{r}
#| label: tidy
#| warning: false

### |- clean and factor variables ----
cats_clean <- cats_data |>
  mutate(
    season = factor(season, levels = c("Summer", "Winter")),
    cat_age = factor(cat_age, levels = c("Junior", "Prime", "Mature")),
    bcs_ord = factor(bcs_ord, levels = c("Ideal", "Overweight", "Heavy", "Obese")),
    housing = factor(housing,
      levels = c("Indoor", "Indoor Outdoor"),
      labels = c("Indoor", "Indoor & Outdoor")
    ),
    area = factor(area, levels = c("Urban", "Rural")),
    cat2 = factor(cat2, levels = c("Single", "Multi")),
    children = factor(children,
      levels = c("No", "Yes"),
      labels = c("No Children", "With Children")
    ),
    dog = factor(dog,
      levels = c("No", "Yes"),
      labels = c("No Dog", "With Dog")
    )
  ) |>
  mutate(
    resting_sec = lying + sitting,
    prop_resting = prop_lying + prop_sitting,
    pct_resting = prop_resting * 100,
    pct_lying = prop_lying * 100,
    pct_sitting = prop_sitting * 100,
    pct_active = prop_active * 100,
    pct_standing = prop_standing * 100,
    pct_grooming = prop_grooming * 100,
    pct_eating = prop_eating * 100,
    pct_scratching = prop_scratching * 100,
    pct_littering = prop_littering * 100
  )

### |- wide format for seasonal comparisons ----
cats_seasonal <- cats_clean |>
  select(
    cat_id, season, pct_resting, pct_lying, pct_sitting, pct_active,
    pct_standing, pct_grooming, pct_eating,
    cat_age, cat_sex, bcs, bcs_ord, housing, area, diet, children, cat2, dog
  ) |>
  pivot_wider(
    names_from = season,
    values_from = c(
      pct_resting, pct_lying, pct_sitting, pct_active,
      pct_standing, pct_grooming, pct_eating
    ),
    names_glue = "{.value}_{season}"
  ) |>
  mutate(
    resting_diff = pct_resting_Winter - pct_resting_Summer,
    resting_avg = (pct_resting_Winter + pct_resting_Summer) / 2,
    active_diff = pct_active_Winter - pct_active_Summer
  ) |>
  # Keep only cats with complete data (n = 28)
  filter(!is.na(pct_resting_Summer) & !is.na(pct_resting_Winter))

### |- prepare environmental effects data ----
env_effects <- cats_clean |>
  select(cat_id, season, pct_resting, children, dog, housing) |>
  pivot_longer(
    cols = c(children, dog),
    names_to = "factor_type",
    values_to = "factor_level"
  ) |>
  mutate(
    factor_type = case_when(
      factor_type == "children" ~ "Children in household",
      factor_type == "dog" ~ "Dog in household"
    ),
    factor_type = factor(factor_type,
      levels = c("Children in household", "Dog in household")
    )
  )

### |- calculate means ----
env_means <- env_effects |>
  group_by(factor_type, factor_level, season) |>
  summarise(
    mean_pct = mean(pct_resting, na.rm = TRUE),
    se_pct = sd(pct_resting, na.rm = TRUE) / sqrt(n()),
    n = n(),
    .groups = "drop"
  )

### |- calculate medians ----
median_summer <- median(cats_seasonal$pct_resting_Summer, na.rm = TRUE)
median_winter <- median(cats_seasonal$pct_resting_Winter, na.rm = TRUE)

# "Lazy band" (most cats spend 70–80% of the day resting)
lazy_low  <- 70
lazy_high <- 80

# data frame for lazy band per facet
lazy_band_df <- tibble(
  factor_type = factor(
    levels(env_effects$factor_type),
    levels = levels(env_effects$factor_type)
  ),
  xmin = -Inf, xmax = Inf,
  ymin = lazy_low, ymax = lazy_high
)
```

5. Visualization Parameters

Show code
```{r}
#| label: params
#| include: true
#| warning: false

### |-  plot aesthetics ----
# Get base colors with custom palette
colors <- get_theme_colors(
  palette = list(
    col_indoor  = "#2C5F8D",
    col_outdoor = "#E07B42",
    col_summer = "#D4952A",
    col_winter = "#6AADC4",
    col_gray = "gray45",
    col_gray_light = "gray70",
    col_grid = "gray92"        
  )
)

### |-  Main titles ----
title_text <- "Pet cats rest 70–80% of the day regardless of season"
subtitle_text <- str_glue(
  "Accelerometer data from 28 New Zealand cats shows most time is spent lying or sitting,<br>",
  "with only small differences by season, housing, or household environment."
)

### |-  Data source caption ----
caption_text <- create_mm_caption(
  mm_year = 2025,
  mm_week = 47,
  source_text = str_glue(
    "Smit et al. (2024) Sensors<br>",
    "**Note:** haded band = 70–80% of day resting | Dashed lines in panel A = medians | Points = individual cats, bars = mean ± SE"
  )
)

### |-  fonts ----
setup_fonts()
fonts <- get_font_families()

### |-  plot theme ----

# Start with base theme
base_theme <- create_base_theme(colors)

# Add weekly-specific theme elements
weekly_theme <- extend_weekly_theme(
  base_theme,
  theme(
    # # Text styling
    plot.title = element_text(
      size = rel(1.5), family = fonts$title, face = "bold",
      color = colors$title, lineheight = 1.1, hjust = 0,
      margin = margin(t = 5, b = 10)
    ),
    plot.subtitle = element_markdown(
      size = rel(0.9), family = fonts$subtitle, face = "italic",
      color = alpha(colors$subtitle, 0.9), lineheight = 1.1,
      margin = margin(t = 0, b = 20)
    ),

    # Legend formatting
    legend.position = "plot",
    legend.justification = "top",
    legend.margin = margin(l = 12, b = 5),
    legend.key.size = unit(0.8, "cm"),
    legend.box.margin = margin(b = 10),
    # legend.title = element_text(face = "bold"),

    # Axis formatting
    axis.ticks.y = element_blank(),
    axis.ticks.x = element_line(color = "gray", linewidth = 0.5),
    
    axis.title.x = element_text(
      face = "bold", size = rel(0.85),
      margin = margin(t = 10), family = fonts$subtitle,
      color = "gray40" 
    ),
    axis.title.y = element_text(
      face = "bold", size = rel(0.85),
      margin = margin(r = 10), family = fonts$subtitle,
      color = "gray40" 
    ),
    axis.text.x = element_text(
      size = rel(0.85), family = fonts$subtitle,
      color = "gray40"  
    ),
    axis.text.y = element_markdown(
      size = rel(0.85), family = fonts$subtitle,
      color = "gray40"
    ),

    # Grid lines
    panel.grid.minor = element_line(color = "#ecf0f1", linewidth = 0.2),
    panel.grid.major = element_line(color = "#ecf0f1", linewidth = 0.4),

    # Margin
    plot.margin = margin(20, 20, 20, 20)
  )
)

# Set theme
theme_set(weekly_theme)
```

6. Plot

Show code
```{r}
#| label: plot
#| warning: false

### |- SCATTER PLOT (Panel A) ----
p1 <- ggplot(cats_seasonal, aes(x = pct_resting_Summer, y = pct_resting_Winter)) +
  # Lazy band
  annotate(
    "rect",
    xmin = lazy_low, xmax = lazy_high,
    ymin = lazy_low, ymax = lazy_high,
    fill = "grey60", alpha = 0.06
  ) +
  # Diagonal & medians
  geom_abline(
    slope = 1, intercept = 0,
    linetype = "dashed", color = colors$palette$col_gray_light, linewidth = 0.7
  ) +
  geom_vline(
    xintercept = median_summer,
    linetype = "dashed", color = colors$palette$col_gray, linewidth = 0.5
  ) +
  geom_hline(
    yintercept = median_winter,
    linetype = "dashed", color = colors$palette$col_gray, linewidth = 0.5
  ) +
  geom_point(aes(color = housing), size = 3.5, alpha = 0.9) +
  # Annotations
  annotate("text",
           x = 57, y = 91,
           label = "More active in summer\nLazier in winter",
           hjust = 0, vjust = 1, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 91.5, y = 91.5,
           label = "Consistently lazy",
           hjust = 1, vjust = 1, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 57, y = 56,
           label = "Consistently active",
           hjust = 0, vjust = 0, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 91.5, y = 56,
           label = "Lazier in summer\nMore active in winter",
           hjust = 1, vjust = 0, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 88, y = 86,
           label = "No change",
           hjust = 1, size = 2.6, color = colors$palette$col_gray_light, angle = 45
  ) +
  # Scales
  scale_color_manual(
    values = c("Indoor" = colors$palette$col_indoor, "Indoor & Outdoor" = colors$palette$col_outdoor),
    name = "Housing:"
  ) +
  coord_fixed(xlim = c(55, 93), ylim = c(55, 93)) +
  # Labs
  labs(
    x = "Summer: % of day spent resting",
    y = "Winter: % of day spent resting"
  ) +
  guides(
    color = guide_legend(override.aes = list(size = 3))
  ) +
  # Theme
  theme(
    legend.position = "top",
    legend.justification = "left",
    legend.title = element_text(face = "bold", size = 9),
    legend.text = element_text(size = 9),
    legend.margin = margin(b = 5),
    legend.box.margin = margin(b = -5),
    panel.grid.minor = element_blank(),
    plot.margin = margin(5, 10, 5, 5)
  )

### |- DOT PLOT (Panel B) ----
p2 <- env_effects |>
  ggplot(aes(x = factor_level, y = pct_resting, color = season)) +
  # Lazy band
  geom_rect(
    data = lazy_band_df,
    aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
    inherit.aes = FALSE,
    fill = "grey60",
    alpha = 0.06
  ) +
  # Individual cats
  geom_point(
    position = position_jitterdodge(jitter.width = 0.12, dodge.width = 0.5, seed = 42),
    alpha = 0.45,
    size = 1.8
  ) +
  # Means with SE
  geom_pointrange(
    data = env_means,
    aes(
      x = factor_level, y = mean_pct,
      ymin = mean_pct - se_pct, ymax = mean_pct + se_pct,
      color = season
    ),
    position = position_dodge(width = 0.5),
    size = 0.6,
    linewidth = 0.7,
    show.legend = FALSE
  ) +
  # Facet
  facet_wrap(~factor_type, scales = "free_x") +
  # Scales
  scale_color_manual(
    values = c("Summer" = colors$palette$col_summer, "Winter" = colors$palette$col_winter),
    name = "Season:"
  ) +
  scale_y_continuous(
    limits = c(55, 93),
    breaks = seq(60, 90, 10),
    labels = label_percent(accuracy = 1, scale = 1)
  ) +
  # Labs
  labs(
    x = NULL,
    y = "% of day spent resting"
  ) +
  guides(
    color = guide_legend(override.aes = list(size = 3))
  ) +
  # Theme
  theme(
    legend.position = "top",
    legend.justification = "left",
    legend.title = element_text(face = "bold", size = 9),
    legend.text = element_text(size = 9),
    legend.margin = margin(b = 5),
    legend.box.margin = margin(b = -5),
    strip.text = element_text(face = "bold", size = 10),
    panel.grid.minor = element_blank(),
    panel.grid.major.x = element_blank(),
    plot.margin = margin(5, 5, 5, 10)
  )

### |- COMBINED PLOTS ----
combined_plots <- p1 + p2 +
  plot_layout(widths = c(1.2, 1)) +
  plot_annotation(
    title = title_text,
    subtitle = subtitle_text,
    caption = caption_text,
    # tag_levels = "A",
    theme = theme(
      plot.title = element_text(
        size = rel(1.95),
        family = fonts$title,
        face = "bold",
        color = colors$title,
        lineheight = 1.1,
        margin = margin(t = 5, b = 5)
      ),
      plot.subtitle = element_markdown(
        size = rel(0.95),
        family = fonts$subtitle,
        color = alpha(colors$subtitle, 0.9),
        lineheight = 1.5,
        margin = margin(t = 5, b = 25)
      ),
      plot.caption = element_markdown(
        size = rel(0.55),
        family = fonts$caption,
        color = 'gray50',
        hjust = 0,
        lineheight = 1.2,
        margin = margin(t = 10, b = 10)
      ),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      axis.ticks = element_blank()
    )
  )
```

7. Save

Show code
```{r}
#| label: save
#| warning: false

### |-  plot image ----  
save_plot_patchwork(
  plot = combined_plots, 
  type = "makeovermonday", 
  year = current_year,
  week = current_week,
  width = 10, 
  height = 8
  )
```

8. Session Info

Expand for Session Info
R version 4.4.1 (2024-06-14 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 26100)

Matrix products: default


locale:
[1] LC_COLLATE=English_United States.utf8 
[2] LC_CTYPE=English_United States.utf8   
[3] LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.utf8    

time zone: America/New_York
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
 [1] here_1.0.1      patchwork_1.3.0 glue_1.8.0      showtext_0.9-7 
 [5] showtextdb_3.0  sysfonts_0.8.9  ggtext_0.1.2    scales_1.3.0   
 [9] skimr_2.1.5     janitor_2.2.0   lubridate_1.9.3 forcats_1.0.0  
[13] stringr_1.5.1   dplyr_1.1.4     purrr_1.0.2     readr_2.1.5    
[17] tidyr_1.3.1     tibble_3.2.1    ggplot2_3.5.1   tidyverse_2.0.0
[21] pacman_0.5.1   

loaded via a namespace (and not attached):
 [1] gtable_0.3.6       xfun_0.49          htmlwidgets_1.6.4  tzdb_0.5.0        
 [5] yulab.utils_0.1.8  vctrs_0.6.5        tools_4.4.0        generics_0.1.3    
 [9] curl_6.0.0         parallel_4.4.0     gifski_1.32.0-1    fansi_1.0.6       
[13] pkgconfig_2.0.3    ggplotify_0.1.2    lifecycle_1.0.4    compiler_4.4.0    
[17] farver_2.1.2       munsell_0.5.1      repr_1.1.7         codetools_0.2-20  
[21] snakecase_0.11.1   htmltools_0.5.8.1  yaml_2.3.10        crayon_1.5.3      
[25] pillar_1.9.0       camcorder_0.1.0    magick_2.8.5       commonmark_1.9.2  
[29] tidyselect_1.2.1   digest_0.6.37      stringi_1.8.4      labeling_0.4.3    
[33] rsvg_2.6.1         rprojroot_2.0.4    fastmap_1.2.0      grid_4.4.0        
[37] colorspace_2.1-1   cli_3.6.4          magrittr_2.0.3     base64enc_0.1-3   
[41] utf8_1.2.4         withr_3.0.2        bit64_4.5.2        timechange_0.3.0  
[45] rmarkdown_2.29     bit_4.5.0          hms_1.1.3          evaluate_1.0.1    
[49] knitr_1.49         markdown_1.13      gridGraphics_0.5-1 rlang_1.1.6       
[53] gridtext_0.1.5     Rcpp_1.0.13-1      xml2_1.3.6         renv_1.0.3        
[57] vroom_1.6.5        svglite_2.1.3      rstudioapi_0.17.1  jsonlite_1.8.9    
[61] R6_2.5.1           fs_1.6.5           systemfonts_1.1.0 

9. GitHub Repository

Expand for GitHub Repo

The complete code for this analysis is available in mm_2025_47.qmd.

For the full repository, click here.

10. References

Expand for References
  1. Data:

    • Makeover Monday 2025 Week 47: Do cats really loaf all day?
  2. Article

    • Do cats really loaf all day?
  3. Citations:

    • Smit, M., Corner-Thomas, R. A., Draganova, I., Andrews, C. J., & Thomas, D. G. (2024). How Lazy Are Pet Cats Really? Using Machine Learning and Accelerometry to Get a Glimpse into the Behaviour of Privately Owned Cats in Different Households. Sensors, 24(8), 2623. https://doi.org/10.3390/s24082623

    • Smit, M. (2023). Weekly data cats for home trial. figshare. Dataset. https://doi.org/10.6084/m9.figshare.24848292.v2

11. Custom Functions Documentation

📦 Custom Helper Functions

This analysis uses custom functions from my personal module library for efficiency and consistency across projects.

Functions Used:

  • fonts.R: setup_fonts(), get_font_families() - Font management with showtext
  • social_icons.R: create_social_caption() - Generates formatted social media captions
  • image_utils.R: save_plot() - Consistent plot saving with naming conventions
  • base_theme.R: create_base_theme(), extend_weekly_theme(), get_theme_colors() - Custom ggplot2 themes

Why custom functions?
These utilities standardize theming, fonts, and output across all my data visualizations. The core analysis (data tidying and visualization logic) uses only standard tidyverse packages.

Source Code:
View all custom functions → GitHub: R/utils

Back to top
Source Code
---
title: "Pet cats rest 70–80% of the day regardless of season"
subtitle: "Accelerometer data from 28 New Zealand cats shows most time is spent lying or sitting, with only small differences by season, housing, or household environment."
description: "A Makeover Monday redesign exploring pet cat activity patterns using accelerometer data. The original icon-based scatter plot is transformed into a clean quadrant chart comparing seasonal resting behavior, paired with a dot plot examining environmental factors like children and dogs in the household."
date: "2025-12-02"
categories: ["MakeoverMonday", "Data Visualization", "R Programming", "2025"]   
tags: [
   "makeover-monday",
  "data-visualization",
  "ggplot2",
  "R",
  "scatter-plot",
  "dot-plot",
  "patchwork",
  "animal-behavior",
  "cats",
  "accelerometer",
  "pet-science",
  "seasonal-analysis",
  "New-Zealand"
]
image: "thumbnails/mm_2025_47.png"
format:
  html:
    toc: true
    toc-depth: 5
    code-link: true
    code-fold: true
    code-tools: true
    code-summary: "Show code"
    self-contained: true
    theme: 
      light: [flatly, assets/styling/custom_styles.scss]
      dark: [darkly, assets/styling/custom_styles_dark.scss]
editor_options: 
  chunk_output_type: inline
execute: 
  freeze: true                                      
  cache: true                                       
  error: false
  message: false
  warning: false
  eval: true
---

```{r}
#| label: setup-links
#| include: false

# CENTRALIZED LINK MANAGEMENT

## Project-specific info 
current_year <- 2025
current_week <- 47
project_file <- "mm_2025_47.qmd"
project_image <- "mm_2025_47.png"

## Data Sources
data_main <- "https://data.world/makeovermonday/2025-week-47-lazy-cats"
data_secondary <- "https://lazy-cats.netlify.app/"

## Repository Links  
repo_main <- "https://github.com/poncest/personal-website/"
repo_file <- paste0("https://github.com/poncest/personal-website/blob/master/data_visualizations/MakeoverMonday/", current_year, "/", project_file)

## External Resources/Images
chart_original <- "https://raw.githubusercontent.com/poncest/MakeoverMonday/refs/heads/master/2025/Week_47/original_chart.png"

## Organization/Platform Links
org_primary <- "https://figshare.com/articles/dataset/How_lazy_are_pet_cats_really_Using_machine_learning_and_accelerometry_to_get_a_glimpse_into_the_behaviour_of_privately_owned_cats_in_different_households/24848292?file=43720347"
org_secondary <- "https://lazy-cats.netlify.app/"

# Helper function to create markdown links
create_link <- function(text, url) {
  paste0("[", text, "](", url, ")")
}

# Helper function for citation-style links
create_citation_link <- function(text, url, title = NULL) {
  if (is.null(title)) {
    paste0("[", text, "](", url, ")")
  } else {
    paste0("[", text, "](", url, ' "', title, '")')
  }
}
```

### Original

The original visualization comes from `r create_link("Do cats really loaf all day?", data_secondary)`

![Original visualization](https://raw.githubusercontent.com/poncest/MakeoverMonday/refs/heads/master/2025/Week_47/original_chart.png)

### Makeover

![Two-panel chart examining cat resting behavior. Left panel: Scatter plot comparing 28 cats' resting time in summer (x-axis) versus winter (y-axis), ranging from 55-90%. Points cluster along the diagonal 'no change' line, mostly within 70-80%, indicating minimal seasonal variation. Blue points represent indoor cats, orange points represent indoor & outdoor cats. Right panel: Dot plots showing resting time by household environment. Cats in homes with children rest slightly less (\~70%) than those without (\~75%), while dog presence shows minimal difference. Individual cats are shown as points with mean ± SE bars overlaid.](mm_2025_47.png){#fig-1}

### <mark> **Steps to Create this Graphic** </mark>

#### 1. Load Packages & Setup

```{r}
#| label: load
#| warning: false
#| message: false      
#| results: "hide"     

## 1. LOAD PACKAGES & SETUP ----
suppressPackageStartupMessages({
  if (!require("pacman")) install.packages("pacman")
  pacman::p_load(
    tidyverse,     # Easily Install and Load the 'Tidyverse'
    janitor,       # Simple Tools for Examining and Cleaning Dirty Data
    skimr,         # Compact and Flexible Summaries of Data
    scales,        # Scale Functions for Visualization
    ggtext,        # Improved Text Rendering Support for 'ggplot2'
    showtext,      # Using Fonts More Easily in R Graphs
    glue,          # Interpreted String Literals
    patchwork      # The Composer of Plots
)
})

### |- figure size ----
camcorder::gg_record(
    dir    = here::here("temp_plots"),
    device = "png",
    width  = 10,
    height = 8,
    units  = "in",
    dpi    = 320
)

# Source utility functions
suppressMessages(source(here::here("R/utils/fonts.R")))
source(here::here("R/utils/social_icons.R"))
source(here::here("R/utils/image_utils.R"))
source(here::here("R/themes/base_theme.R"))
```

#### 2. Read in the Data

```{r}
#| label: read
#| include: true
#| eval: true
#| warning: false
#| 

cats_data <- read_csv(
  here::here("data/MakeoverMonday/2025/cats_data.csv")) |>
  clean_names()
```

#### 3. Examine the Data

```{r}
#| label: examine
#| include: true
#| eval: true
#| results: 'hide'
#| warning: false

glimpse(cats_data)
skim(cats_data) |> summary()
```

#### 4. Tidy Data

```{r}
#| label: tidy
#| warning: false

### |- clean and factor variables ----
cats_clean <- cats_data |>
  mutate(
    season = factor(season, levels = c("Summer", "Winter")),
    cat_age = factor(cat_age, levels = c("Junior", "Prime", "Mature")),
    bcs_ord = factor(bcs_ord, levels = c("Ideal", "Overweight", "Heavy", "Obese")),
    housing = factor(housing,
      levels = c("Indoor", "Indoor Outdoor"),
      labels = c("Indoor", "Indoor & Outdoor")
    ),
    area = factor(area, levels = c("Urban", "Rural")),
    cat2 = factor(cat2, levels = c("Single", "Multi")),
    children = factor(children,
      levels = c("No", "Yes"),
      labels = c("No Children", "With Children")
    ),
    dog = factor(dog,
      levels = c("No", "Yes"),
      labels = c("No Dog", "With Dog")
    )
  ) |>
  mutate(
    resting_sec = lying + sitting,
    prop_resting = prop_lying + prop_sitting,
    pct_resting = prop_resting * 100,
    pct_lying = prop_lying * 100,
    pct_sitting = prop_sitting * 100,
    pct_active = prop_active * 100,
    pct_standing = prop_standing * 100,
    pct_grooming = prop_grooming * 100,
    pct_eating = prop_eating * 100,
    pct_scratching = prop_scratching * 100,
    pct_littering = prop_littering * 100
  )

### |- wide format for seasonal comparisons ----
cats_seasonal <- cats_clean |>
  select(
    cat_id, season, pct_resting, pct_lying, pct_sitting, pct_active,
    pct_standing, pct_grooming, pct_eating,
    cat_age, cat_sex, bcs, bcs_ord, housing, area, diet, children, cat2, dog
  ) |>
  pivot_wider(
    names_from = season,
    values_from = c(
      pct_resting, pct_lying, pct_sitting, pct_active,
      pct_standing, pct_grooming, pct_eating
    ),
    names_glue = "{.value}_{season}"
  ) |>
  mutate(
    resting_diff = pct_resting_Winter - pct_resting_Summer,
    resting_avg = (pct_resting_Winter + pct_resting_Summer) / 2,
    active_diff = pct_active_Winter - pct_active_Summer
  ) |>
  # Keep only cats with complete data (n = 28)
  filter(!is.na(pct_resting_Summer) & !is.na(pct_resting_Winter))

### |- prepare environmental effects data ----
env_effects <- cats_clean |>
  select(cat_id, season, pct_resting, children, dog, housing) |>
  pivot_longer(
    cols = c(children, dog),
    names_to = "factor_type",
    values_to = "factor_level"
  ) |>
  mutate(
    factor_type = case_when(
      factor_type == "children" ~ "Children in household",
      factor_type == "dog" ~ "Dog in household"
    ),
    factor_type = factor(factor_type,
      levels = c("Children in household", "Dog in household")
    )
  )

### |- calculate means ----
env_means <- env_effects |>
  group_by(factor_type, factor_level, season) |>
  summarise(
    mean_pct = mean(pct_resting, na.rm = TRUE),
    se_pct = sd(pct_resting, na.rm = TRUE) / sqrt(n()),
    n = n(),
    .groups = "drop"
  )

### |- calculate medians ----
median_summer <- median(cats_seasonal$pct_resting_Summer, na.rm = TRUE)
median_winter <- median(cats_seasonal$pct_resting_Winter, na.rm = TRUE)

# "Lazy band" (most cats spend 70–80% of the day resting)
lazy_low  <- 70
lazy_high <- 80

# data frame for lazy band per facet
lazy_band_df <- tibble(
  factor_type = factor(
    levels(env_effects$factor_type),
    levels = levels(env_effects$factor_type)
  ),
  xmin = -Inf, xmax = Inf,
  ymin = lazy_low, ymax = lazy_high
)
```

#### 5. Visualization Parameters

```{r}
#| label: params
#| include: true
#| warning: false

### |-  plot aesthetics ----
# Get base colors with custom palette
colors <- get_theme_colors(
  palette = list(
    col_indoor  = "#2C5F8D",
    col_outdoor = "#E07B42",
    col_summer = "#D4952A",
    col_winter = "#6AADC4",
    col_gray = "gray45",
    col_gray_light = "gray70",
    col_grid = "gray92"        
  )
)

### |-  Main titles ----
title_text <- "Pet cats rest 70–80% of the day regardless of season"
subtitle_text <- str_glue(
  "Accelerometer data from 28 New Zealand cats shows most time is spent lying or sitting,<br>",
  "with only small differences by season, housing, or household environment."
)

### |-  Data source caption ----
caption_text <- create_mm_caption(
  mm_year = 2025,
  mm_week = 47,
  source_text = str_glue(
    "Smit et al. (2024) Sensors<br>",
    "**Note:** haded band = 70–80% of day resting | Dashed lines in panel A = medians | Points = individual cats, bars = mean ± SE"
  )
)

### |-  fonts ----
setup_fonts()
fonts <- get_font_families()

### |-  plot theme ----

# Start with base theme
base_theme <- create_base_theme(colors)

# Add weekly-specific theme elements
weekly_theme <- extend_weekly_theme(
  base_theme,
  theme(
    # # Text styling
    plot.title = element_text(
      size = rel(1.5), family = fonts$title, face = "bold",
      color = colors$title, lineheight = 1.1, hjust = 0,
      margin = margin(t = 5, b = 10)
    ),
    plot.subtitle = element_markdown(
      size = rel(0.9), family = fonts$subtitle, face = "italic",
      color = alpha(colors$subtitle, 0.9), lineheight = 1.1,
      margin = margin(t = 0, b = 20)
    ),

    # Legend formatting
    legend.position = "plot",
    legend.justification = "top",
    legend.margin = margin(l = 12, b = 5),
    legend.key.size = unit(0.8, "cm"),
    legend.box.margin = margin(b = 10),
    # legend.title = element_text(face = "bold"),

    # Axis formatting
    axis.ticks.y = element_blank(),
    axis.ticks.x = element_line(color = "gray", linewidth = 0.5),
    
    axis.title.x = element_text(
      face = "bold", size = rel(0.85),
      margin = margin(t = 10), family = fonts$subtitle,
      color = "gray40" 
    ),
    axis.title.y = element_text(
      face = "bold", size = rel(0.85),
      margin = margin(r = 10), family = fonts$subtitle,
      color = "gray40" 
    ),
    axis.text.x = element_text(
      size = rel(0.85), family = fonts$subtitle,
      color = "gray40"  
    ),
    axis.text.y = element_markdown(
      size = rel(0.85), family = fonts$subtitle,
      color = "gray40"
    ),

    # Grid lines
    panel.grid.minor = element_line(color = "#ecf0f1", linewidth = 0.2),
    panel.grid.major = element_line(color = "#ecf0f1", linewidth = 0.4),

    # Margin
    plot.margin = margin(20, 20, 20, 20)
  )
)

# Set theme
theme_set(weekly_theme)
```

#### 6. Plot

```{r}
#| label: plot
#| warning: false

### |- SCATTER PLOT (Panel A) ----
p1 <- ggplot(cats_seasonal, aes(x = pct_resting_Summer, y = pct_resting_Winter)) +
  # Lazy band
  annotate(
    "rect",
    xmin = lazy_low, xmax = lazy_high,
    ymin = lazy_low, ymax = lazy_high,
    fill = "grey60", alpha = 0.06
  ) +
  # Diagonal & medians
  geom_abline(
    slope = 1, intercept = 0,
    linetype = "dashed", color = colors$palette$col_gray_light, linewidth = 0.7
  ) +
  geom_vline(
    xintercept = median_summer,
    linetype = "dashed", color = colors$palette$col_gray, linewidth = 0.5
  ) +
  geom_hline(
    yintercept = median_winter,
    linetype = "dashed", color = colors$palette$col_gray, linewidth = 0.5
  ) +
  geom_point(aes(color = housing), size = 3.5, alpha = 0.9) +
  # Annotations
  annotate("text",
           x = 57, y = 91,
           label = "More active in summer\nLazier in winter",
           hjust = 0, vjust = 1, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 91.5, y = 91.5,
           label = "Consistently lazy",
           hjust = 1, vjust = 1, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 57, y = 56,
           label = "Consistently active",
           hjust = 0, vjust = 0, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 91.5, y = 56,
           label = "Lazier in summer\nMore active in winter",
           hjust = 1, vjust = 0, size = 2.8, color = colors$palette$col_gray
  ) +
  annotate("text",
           x = 88, y = 86,
           label = "No change",
           hjust = 1, size = 2.6, color = colors$palette$col_gray_light, angle = 45
  ) +
  # Scales
  scale_color_manual(
    values = c("Indoor" = colors$palette$col_indoor, "Indoor & Outdoor" = colors$palette$col_outdoor),
    name = "Housing:"
  ) +
  coord_fixed(xlim = c(55, 93), ylim = c(55, 93)) +
  # Labs
  labs(
    x = "Summer: % of day spent resting",
    y = "Winter: % of day spent resting"
  ) +
  guides(
    color = guide_legend(override.aes = list(size = 3))
  ) +
  # Theme
  theme(
    legend.position = "top",
    legend.justification = "left",
    legend.title = element_text(face = "bold", size = 9),
    legend.text = element_text(size = 9),
    legend.margin = margin(b = 5),
    legend.box.margin = margin(b = -5),
    panel.grid.minor = element_blank(),
    plot.margin = margin(5, 10, 5, 5)
  )

### |- DOT PLOT (Panel B) ----
p2 <- env_effects |>
  ggplot(aes(x = factor_level, y = pct_resting, color = season)) +
  # Lazy band
  geom_rect(
    data = lazy_band_df,
    aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
    inherit.aes = FALSE,
    fill = "grey60",
    alpha = 0.06
  ) +
  # Individual cats
  geom_point(
    position = position_jitterdodge(jitter.width = 0.12, dodge.width = 0.5, seed = 42),
    alpha = 0.45,
    size = 1.8
  ) +
  # Means with SE
  geom_pointrange(
    data = env_means,
    aes(
      x = factor_level, y = mean_pct,
      ymin = mean_pct - se_pct, ymax = mean_pct + se_pct,
      color = season
    ),
    position = position_dodge(width = 0.5),
    size = 0.6,
    linewidth = 0.7,
    show.legend = FALSE
  ) +
  # Facet
  facet_wrap(~factor_type, scales = "free_x") +
  # Scales
  scale_color_manual(
    values = c("Summer" = colors$palette$col_summer, "Winter" = colors$palette$col_winter),
    name = "Season:"
  ) +
  scale_y_continuous(
    limits = c(55, 93),
    breaks = seq(60, 90, 10),
    labels = label_percent(accuracy = 1, scale = 1)
  ) +
  # Labs
  labs(
    x = NULL,
    y = "% of day spent resting"
  ) +
  guides(
    color = guide_legend(override.aes = list(size = 3))
  ) +
  # Theme
  theme(
    legend.position = "top",
    legend.justification = "left",
    legend.title = element_text(face = "bold", size = 9),
    legend.text = element_text(size = 9),
    legend.margin = margin(b = 5),
    legend.box.margin = margin(b = -5),
    strip.text = element_text(face = "bold", size = 10),
    panel.grid.minor = element_blank(),
    panel.grid.major.x = element_blank(),
    plot.margin = margin(5, 5, 5, 10)
  )

### |- COMBINED PLOTS ----
combined_plots <- p1 + p2 +
  plot_layout(widths = c(1.2, 1)) +
  plot_annotation(
    title = title_text,
    subtitle = subtitle_text,
    caption = caption_text,
    # tag_levels = "A",
    theme = theme(
      plot.title = element_text(
        size = rel(1.95),
        family = fonts$title,
        face = "bold",
        color = colors$title,
        lineheight = 1.1,
        margin = margin(t = 5, b = 5)
      ),
      plot.subtitle = element_markdown(
        size = rel(0.95),
        family = fonts$subtitle,
        color = alpha(colors$subtitle, 0.9),
        lineheight = 1.5,
        margin = margin(t = 5, b = 25)
      ),
      plot.caption = element_markdown(
        size = rel(0.55),
        family = fonts$caption,
        color = 'gray50',
        hjust = 0,
        lineheight = 1.2,
        margin = margin(t = 10, b = 10)
      ),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      axis.ticks = element_blank()
    )
  )
```

#### 7. Save

```{r}
#| label: save
#| warning: false

### |-  plot image ----  
save_plot_patchwork(
  plot = combined_plots, 
  type = "makeovermonday", 
  year = current_year,
  week = current_week,
  width = 10, 
  height = 8
  )
```

#### 8. Session Info

::: {.callout-tip collapse="true"}
##### Expand for Session Info

```{r, echo = FALSE}
#| eval: true
#| warning: false

sessionInfo()
```
:::

#### 9. GitHub Repository

::: {.callout-tip collapse="true"}
##### Expand for GitHub Repo

The complete code for this analysis is available in `r create_link(project_file, repo_file)`.

For the full repository, `r create_link("click here", repo_main)`.
:::

#### 10. References

::: {.callout-tip collapse="true"}
##### Expand for References

1.  Data:

    -   Makeover Monday `r current_year` Week `r current_week`: `r create_link("Do cats really loaf all day?", data_main)`

2.  Article

    -   `r create_link("Do cats really loaf all day?", data_secondary)`

3.  Citations:

    -   Smit, M., Corner-Thomas, R. A., Draganova, I., Andrews, C. J., & Thomas, D. G. (2024). **How Lazy Are Pet Cats Really? Using Machine Learning and Accelerometry to Get a Glimpse into the Behaviour of Privately Owned Cats in Different Households.** *Sensors, 24*(8), 2623. <https://doi.org/10.3390/s24082623>

    -   Smit, M. (2023). **Weekly data cats for home trial.** figshare. Dataset. <https://doi.org/10.6084/m9.figshare.24848292.v2>
:::

#### 11. Custom Functions Documentation

::: {.callout-note collapse="true"}
##### 📦 Custom Helper Functions

This analysis uses custom functions from my personal module library for efficiency and consistency across projects.

**Functions Used:**

-   **`fonts.R`**: `setup_fonts()`, `get_font_families()` - Font management with showtext
-   **`social_icons.R`**: `create_social_caption()` - Generates formatted social media captions
-   **`image_utils.R`**: `save_plot()` - Consistent plot saving with naming conventions
-   **`base_theme.R`**: `create_base_theme()`, `extend_weekly_theme()`, `get_theme_colors()` - Custom ggplot2 themes

**Why custom functions?**\
These utilities standardize theming, fonts, and output across all my data visualizations. The core analysis (data tidying and visualization logic) uses only standard tidyverse packages.

**Source Code:**\
View all custom functions → [GitHub: R/utils](https://github.com/poncest/personal-website/tree/master/R)
:::

© 2024 Steven Ponce

Source Issues