Introduction

Row

Overview

The Quantified Self (QS) movement leverages wearables, analytics, and “Big Data” to gain insights about personal health patterns. With the rise of smart devices and fitness trackers, collecting data about individual bodies and behaviors has never been easier. Sleep, being a critical aspect of health that occupies roughly one-third of lives, provides a wealth of quantifiable information about wellbeing.

Modern sleep tracking technology allows monitoring not just duration, but sleep stages, quality metrics, and physiological responses during rest. This dashboard explores sleep patterns using data collected through Samsung Health, demonstrating the power of personal informatics to generate meaningful insights into daily life and health behaviors.

Row

Objective

The objective of this dashboard is to analyze sleep data to identify patterns, trends, and potential areas for improvement in sleep health. To accomplish this, several key steps were completed:

  1. Collection and organization of sleep data from Samsung Health’s sleep tracking feature
  2. Processing and preparation of data for meaningful analysis, including extraction of day of week information and calculation of derived metrics
  3. Design of multiple visualization types (bar charts, line graphs, heatmaps, scatter plots) that best represent different aspects of sleep patterns
  4. Creation of an interactive dashboard that allows for exploration of relationships between different sleep variables
  5. Generation of insights and recommendations based on the observed patterns in the sleep data

Five Questions to answer through this analysis

  1. What patterns exist in my sleep duration and quality across different days of the week?
  2. How does my average sleep duration differ between weekdays and weekends?
  3. Is there a measurable relationship between my bedtime and overall sleep quality?
  4. How are my sleep stages (REM, Light, Deep) distributed, and how does this compare to healthy benchmarks?
  5. How consistent is my sleep schedule throughout the week, and does consistency correlate with better sleep quality?

Methodology & Summary

Row

Data Acquisition & Processing

The sleep data analyzed in this dashboard was collected over a two-month period (February-April 2025) using a Samsung Galaxy Watch connected to a Samsung S24 Ultra smartphone. The Galaxy Watch employs multiple sensors to track sleep metrics, including accelerometer, heart rate monitor, blood oxygen (SpO₂) sensor, and temperature sensors. These combined measurements enable the device to detect sleep onset, disturbances, awakenings, and distinguish between different sleep stages.

The Samsung Health application automatically processed the raw sensor data into structured sleep metrics, which were then exported as a CSV file containing 60 nights of sleep records with 17 distinct parameters per night. This dataset formed the foundation for deeper analysis using R programming language and associated visualization packages.

Analytical Framework & Techniques

The analysis employed a multi-dimensional approach examining four key aspects of sleep health:

  1. Duration Analysis: Quantitative examination of sleep length across different time periods and contexts
  2. Quality Analysis: Investigation of sleep scores, efficiency metrics, and factors affecting overall sleep quality
  3. Composition Analysis: Assessment of sleep stage distribution (REM, Light, Deep) and comparison to clinical benchmarks
  4. Consistency Analysis: Evaluation of sleep pattern regularity including bedtime consistency and duration variability

The data preparation process involved several key steps: extracting temporal information (day of week) from dates, categorizing nights as weekday or weekend, calculating derived metrics such as sleep stage percentages, and transforming time data for correlation analyses. Visualization techniques were selected to optimally represent different aspects of sleep patterns, including time series, comparative charts, distribution analyses, and relationship visualizations.

Key Findings Summary

  1. Duration Deficit: Average sleep duration (6.5 hours) consistently falls below clinical recommendations, with Sunday showing the lowest duration (5.9 hours) and Friday the highest (7.0 hours). Weekday sleep slightly exceeds weekend sleep duration, contrary to typical recovery patterns.

  2. Quality-Timing Relationship: Earlier bedtimes (before 11 PM) strongly correlate with improved sleep quality scores, with the relationship becoming more pronounced after midnight. Tuesday yields the highest average quality while Sunday shows the lowest.

  3. Atypical Sleep Composition: Sleep stage distribution shows higher-than-average deep sleep (46% vs. typical 15-25%) and lower REM sleep (15% vs. typical 20-25%), suggesting excellent physical recovery but potentially reduced cognitive processing during sleep.

  4. Consistency Challenges: Significant bedtime variability (2-3 hour range) observed throughout the week likely disrupts circadian rhythms and contributes to diminished sleep quality despite high efficiency metrics.

  5. Optimization Opportunities: The analysis reveals targeted opportunities for sleep improvement, primarily focusing on extending duration (particularly Sunday nights), establishing earlier and more consistent bedtimes, and maintaining more regular sleep-wake patterns.

Row

Dataset Preview

Sleep Duration Analysis

Row

Overview of Sleep Duration Patterns

The dataset, collected via Samsung Health, captures comprehensive sleep metrics over a two-month period from February to April 2025. Sleep duration represents one of the most critical indicators of sleep health, with clinical guidelines recommending 7-9 hours nightly for optimal adult functioning.

The visualizations uncover distinct sleep duration patterns across the week, revealing unexpected differences between weekdays and weekends. This analysis examines sleep duration from three complementary perspectives:

  • Daily patterns: How sleep duration varies across specific days of the week
  • Weekday vs Weekend comparison: Contrasting sleep habits between work days and rest days
  • Temporal trends: How sleep patterns evolve throughout the collection period

Together, these analyses provide actionable insights into sleep consistency, potential sleep deficits, and targeted opportunities for sleep optimization.

Row

Daily Sleep Duration Patterns

Weekday vs Weekend Sleep Comparison

Sleep Quality Analysis

Row

Overview of Sleep Quality Patterns

The dataset from Samsung Health provides comprehensive metrics not only for sleep duration but also for sleep quality. Sleep quality measures include the Sleep Score, Sleep Efficiency (%), and time spent in different sleep stages. While duration focuses on quantity, quality metrics offer insights into the restorative nature of sleep.

This analysis explores sleep quality from three key perspectives:

  • Quality by day of week: How sleep quality scores vary across different days
  • Bedtime vs sleep quality: The relationship between when sleep begins and its overall quality
  • Sleep efficiency patterns: How effectively sleep time is utilized throughout the week

Understanding these quality dimensions complements duration analysis and provides a more complete picture of sleep health, potentially revealing factors that affect sleep beyond simple duration measures.

Row

Quality by Day of Week

Bedtime vs Sleep Quality

Sleep Efficiency Patterns

Sleep Composition Analysis

Row

Overview of Sleep Composition Patterns

Sleep composition refers to the different stages of sleep experienced throughout the night. The Samsung Health data captures three primary sleep stages: REM (Rapid Eye Movement), Light, and Deep sleep, as well as time spent Awake. These stages are crucial indicators of sleep quality and restorative value.

REM sleep is associated with dreaming and memory consolidation, while deep sleep provides the most restorative benefits. Light sleep serves as a transition between other stages. The ideal sleep composition varies by age, but for adults, a healthy distribution typically includes 20-25% REM, 50-60% light, and 15-25% deep sleep.

This analysis examines sleep composition from two perspectives: - Sleep stages distribution: The breakdown of time spent in each sleep stage - Comparison across different periods: How sleep composition varies between weekdays and weekends

Understanding sleep stage composition can provide insights into sleep quality beyond duration and efficiency metrics, potentially revealing factors affecting overall sleep health.

Row

Sleep Stages Distribution

Comparison of Sleep Stages

Sleep Stages Over Time

Sleep Consistency Analysis

Row

Overview of Sleep Consistency Patterns

Sleep consistency refers to the regularity of sleep patterns over time, including consistent bedtimes, wake times, and total sleep duration. Research suggests that maintaining regular sleep patterns may be as important as sleep duration for overall health and wellbeing. Irregular sleep patterns have been associated with poorer health outcomes including increased risk of cardiovascular disease, metabolic disorders, and mood disturbances.

The Samsung Health data allows for detailed analysis of sleep consistency through metrics such as bedtime variability and sleep duration fluctuations. This analysis examines sleep consistency from two key perspectives:

  • Bedtime consistency: How regular bedtime patterns are across days of the week
  • Sleep duration variability: How much total sleep time fluctuates over the collection period

Understanding these patterns can reveal opportunities to improve sleep hygiene practices and potentially enhance overall sleep quality and health outcomes.

Row

Bedtime Consistency

Sleep Duration Variability

Consistency Metrics

Interactive Sleep Exploration

Row

Interactive Sleep Data Analysis

The interactive exploration section allows for dynamic analysis of sleep patterns across different metrics. Plotly’s built-in controls enable filtering, zooming, and hovering to explore specific data points of interest. The visualizations below provide three complementary perspectives:

  1. Sleep metrics across days of week: Compare how key sleep metrics vary across different days
  2. Sleep metric correlations: Examine relationships between different sleep parameters
  3. Sleep pattern trends over time: Track how sleep patterns have evolved throughout the data collection period

These interactive visualizations allow for deeper insights beyond the static analyses in previous sections, helping to identify potential factors influencing sleep quality and patterns.

Row

Sleep Metrics by Day of Week

Sleep Metric Correlations

Conclusions & Optimization Strategy

Row

Summary of Sleep Pattern Analysis

The comprehensive analysis of sleep data from Samsung Health has provided valuable insights into sleep patterns across duration, quality, composition, and consistency dimensions. These insights can inform targeted interventions to improve overall sleep health.

Key Finding Description Optimization Strategy
Duration Deficit Average sleep duration (6.5 hours) consistently falls below the recommended 7-9 hours for adults, with Sunday showing the lowest duration (5.9 hours). Aim to extend sleep duration by 30-60 minutes, with particular focus on Sunday nights. Consider establishing an earlier bedtime routine on Sundays to prepare for the work week.
Weekday-Weekend Inversion Contrary to typical patterns, weekday sleep (6.6 hours) exceeds weekend sleep (6.3 hours), suggesting inadequate recovery sleep during weekends. Prioritize consistent sleep duration through the entire week, avoiding the temptation to dramatically shift weekend sleep patterns. If social obligations affect weekend sleep, consider compensatory naps when possible.
Bedtime Impact on Quality Earlier bedtimes (before 11 PM) correlate with higher sleep quality scores, with quality declining for bedtimes after midnight. Establish a consistent sleep schedule with target bedtime before 11 PM when possible. Create a wind-down routine 30-60 minutes before bedtime to facilitate falling asleep earlier.
Deep Sleep Abundance Sleep composition shows higher-than-average deep sleep (46%) with somewhat lower REM sleep (15%), which may affect cognitive functions. While the abundance of deep sleep is positive for physical recovery, strategies to improve REM sleep might include: reducing alcohol consumption, managing stress, and ensuring adequate total sleep time to allow for complete sleep cycles.
Schedule Irregularity Significant bedtime variability (2-3 hour range) and moderate duration variability (SD = 30 min) indicate inconsistent sleep patterns that may reduce overall sleep quality. Aim to maintain consistent sleep and wake times within a 30-minute window, even on weekends. Use a sleep tracking app with bedtime reminders to establish regularity in the sleep-wake cycle.
---
title: "Sleep Pattern Analysis Dashboard"
author: "Jijo George"
date: "`r Sys.Date()`"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    Horizontal_layout: fill
    social: menu
    source: embed
    html_document: default
    df_print: paged
    pdf_document: default
---
```{r}
# Set default repository for the session
options(repos = c(CRAN = "https://cloud.r-project.org/"))

# Install required packages
if (!require("flexdashboard")) install.packages("flexdashboard", quiet = TRUE)
if (!require("dygraphs")) install.packages("dygraphs", quiet = TRUE)
if (!require("xts")) install.packages("xts", quiet = TRUE)
if (!require("dplyr")) install.packages("dplyr", quiet = TRUE)
if (!require("ggplot2")) install.packages("ggplot2", quiet = TRUE)
if (!require("readr")) install.packages("readr", quiet = TRUE)
if (!require("plotly")) install.packages("plotly", quiet = TRUE)
if (!require("DT")) install.packages("DT", quiet = TRUE)
if (!require("tidyr")) install.packages("tidyr", quiet = TRUE)
if (!require("lubridate")) install.packages("lubridate", quiet = TRUE)
if (!require("viridis")) install.packages("viridis", quiet = TRUE)
if (!require("tidyverse")) install.packages("tidyverse", quiet = TRUE)
if (!require("shiny")) install.packages("shiny", quiet = TRUE)


# Load required libraries
library(flexdashboard)
library(dygraphs)
library(xts)
library(dplyr)
library(ggplot2)
library(readr)
library(lubridate)
library(plotly)
library(DT)
library(tidyr)
library(viridis)
library(shiny)
```

# Table of Contents {.sidebar}

* [Introduction](#introduction)

* [Methodology & Summary](#methodology-summary)

* [Sleep Duration Analysis](#sleep-duration-analysis)
  - [Daily Sleep Duration Patterns](#daily-sleep-duration)
  - [Weekday vs Weekend Sleep](#weekday-weekend-comparison)
  - [Sleep Duration Trends](#sleep-duration-trends)
  
* [Sleep Quality Analysis](#sleep-quality-analysis)
  - [Quality by Day of Week](#quality-by-day)
  - [Bedtime vs Sleep Quality](#bedtime-quality-relationship)
  - [Sleep Efficiency Patterns](#sleep-efficiency-patterns)
  
* [Sleep Composition Analysis](#sleep-composition-analysis)
  - [Sleep Stages Distribution](#sleep-stages-distribution)
  - [Comparison of Sleep Stages](#sleep-stages-comparison)
  
* [Sleep Consistency Analysis](#sleep-consistency-analysis)
  - [Bedtime Consistency](#bedtime-consistency)
  - [Sleep Duration Variability](#sleep-duration-variability)
  
* [Interactive Sleep Exploration](#interactive-exploration)
  
* [Conclusions & Recommendations](#conclusions)


# **Introduction**
Row {data-height=230}
-------------------------------------
    
### **Overview** 

The Quantified Self (QS) movement leverages wearables, analytics, and "Big Data" to gain insights about personal health patterns. With the rise of smart devices and fitness trackers, collecting data about individual bodies and behaviors has never been easier. Sleep, being a critical aspect of health that occupies roughly one-third of lives, provides a wealth of quantifiable information about wellbeing. 

Modern sleep tracking technology allows monitoring not just duration, but sleep stages, quality metrics, and physiological responses during rest. This dashboard explores sleep patterns using data collected through Samsung Health, demonstrating the power of personal informatics to generate meaningful insights into daily life and health behaviors.

Row
-------------------------------------
    
### **Objective** 

The objective of this dashboard is to analyze sleep data to identify patterns, trends, and potential areas for improvement in sleep health. To accomplish this, several key steps were completed:
  
1. Collection and organization of sleep data from Samsung Health's sleep tracking feature
2. Processing and preparation of data for meaningful analysis, including extraction of day of week information and calculation of derived metrics
3. Design of multiple visualization types (bar charts, line graphs, heatmaps, scatter plots) that best represent different aspects of sleep patterns
4. Creation of an interactive dashboard that allows for exploration of relationships between different sleep variables
5. Generation of insights and recommendations based on the observed patterns in the sleep data


### **Five Questions to answer through this analysis**

1. What patterns exist in my sleep duration and quality across different days of the week?
2. How does my average sleep duration differ between weekdays and weekends?
3. Is there a measurable relationship between my bedtime and overall sleep quality?
4. How are my sleep stages (REM, Light, Deep) distributed, and how does this compare to healthy benchmarks?
5. How consistent is my sleep schedule throughout the week, and does consistency correlate with better sleep quality?


# **Methodology & Summary**

Row {.tabset .tabset-fade data-height=110}
-------------------------------------

### **Data Acquisition & Processing**

The sleep data analyzed in this dashboard was collected over a two-month period (February-April 2025) using a Samsung Galaxy Watch connected to a Samsung S24 Ultra smartphone. The Galaxy Watch employs multiple sensors to track sleep metrics, including accelerometer, heart rate monitor, blood oxygen (SpO₂) sensor, and temperature sensors. These combined measurements enable the device to detect sleep onset, disturbances, awakenings, and distinguish between different sleep stages.

The Samsung Health application automatically processed the raw sensor data into structured sleep metrics, which were then exported as a CSV file containing 60 nights of sleep records with 17 distinct parameters per night. This dataset formed the foundation for deeper analysis using R programming language and associated visualization packages.

### **Analytical Framework & Techniques**

The analysis employed a multi-dimensional approach examining four key aspects of sleep health:
  
1. **Duration Analysis:** Quantitative examination of sleep length across different time periods and contexts
2. **Quality Analysis:** Investigation of sleep scores, efficiency metrics, and factors affecting overall sleep quality
3. **Composition Analysis:** Assessment of sleep stage distribution (REM, Light, Deep) and comparison to clinical benchmarks
4. **Consistency Analysis:** Evaluation of sleep pattern regularity including bedtime consistency and duration variability

The data preparation process involved several key steps: extracting temporal information (day of week) from dates, categorizing nights as weekday or weekend, calculating derived metrics such as sleep stage percentages, and transforming time data for correlation analyses. Visualization techniques were selected to optimally represent different aspects of sleep patterns, including time series, comparative charts, distribution analyses, and relationship visualizations.

### **Key Findings Summary**

1. **Duration Deficit:** Average sleep duration (6.5 hours) consistently falls below clinical recommendations, with Sunday showing the lowest duration (5.9 hours) and Friday the highest (7.0 hours). Weekday sleep slightly exceeds weekend sleep duration, contrary to typical recovery patterns.

2. **Quality-Timing Relationship:** Earlier bedtimes (before 11 PM) strongly correlate with improved sleep quality scores, with the relationship becoming more pronounced after midnight. Tuesday yields the highest average quality while Sunday shows the lowest.

3. **Atypical Sleep Composition:** Sleep stage distribution shows higher-than-average deep sleep (46% vs. typical 15-25%) and lower REM sleep (15% vs. typical 20-25%), suggesting excellent physical recovery but potentially reduced cognitive processing during sleep.

4. **Consistency Challenges:** Significant bedtime variability (2-3 hour range) observed throughout the week likely disrupts circadian rhythms and contributes to diminished sleep quality despite high efficiency metrics.

5. **Optimization Opportunities:** The analysis reveals targeted opportunities for sleep improvement, primarily focusing on extending duration (particularly Sunday nights), establishing earlier and more consistent bedtimes, and maintaining more regular sleep-wake patterns.

Row {data-height=200}
-------------------------------------

### **Dataset Preview**

```{r, echo=FALSE}
sleep_data <- read_csv("C:\\Harrisburg_University\\Semester 3_ANLY 512-90-Data Visualization\\Course Project\\Sleep_Data.csv")

library(DT)
datatable(head(sleep_data, 10), 
          options = list(
            pageLength = 5,
            scrollX = TRUE,
            scrollY = "120px",
            scroller = TRUE,
            dom = 'frti',
            searching = TRUE
          ),
          rownames = FALSE,
          caption = "First 10 records of Sleep Data from Samsung Health") %>%
  formatRound(columns = c('Sleep Efficiency (%)', 'SpO₂ Min (%)', 'SpO₂ Avg (%)'), digits = 1) %>%
  formatRound(columns = c('Skin Temperature Deviation (°C)'), digits = 2)

```


# **Sleep Duration Analysis**

Row {data-height=180}
------------------------

### **Overview of Sleep Duration Patterns**

The dataset, collected via **Samsung Health**, captures comprehensive sleep metrics over a two-month period from February to April 2025. Sleep duration represents one of the most critical indicators of sleep health, with clinical guidelines recommending 7-9 hours nightly for optimal adult functioning.

The visualizations uncover distinct sleep duration patterns across the week, revealing unexpected differences between weekdays and weekends. This analysis examines sleep duration from three complementary perspectives:

- **Daily patterns**: How sleep duration varies across specific days of the week
- **Weekday vs Weekend comparison**: Contrasting sleep habits between work days and rest days
- **Temporal trends**: How sleep patterns evolve throughout the collection period

Together, these analyses provide actionable insights into sleep consistency, potential sleep deficits, and targeted opportunities for sleep optimization.

Row {.tabset .tabset-fade data-width=550}
------------------------

### **Daily Sleep Duration Patterns**
```{r}
# Create Day_of_Week column from Date
sleep_data <- sleep_data %>%
  mutate(
    Date = as.Date(Date, format = "%m/%d/%Y"),
    Day_of_Week = weekdays(Date)
  )

# Calculate average sleep duration by day of week
sleep_by_day <- sleep_data %>%
  mutate(Day_of_Week = factor(Day_of_Week, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))) %>%
  group_by(Day_of_Week) %>%
  summarize(
    Avg_Duration_Min = mean(`Total Sleep Duration (min)`),
    Avg_Duration_Hours = Avg_Duration_Min / 60,
    SD_Duration_Hours = sd(`Total Sleep Duration (min)`) / 60,
    Count = n()
  )

# Create interactive bar chart for sleep duration by day of week
plot_ly(sleep_by_day, x = ~Day_of_Week, y = ~Avg_Duration_Hours, type = 'bar',
        error_y = list(type = 'data', array = ~SD_Duration_Hours, visible = TRUE),
        marker = list(color = viridis(7, alpha = 0.8)),
        text = ~paste("Day:", Day_of_Week, 
                      "<br>Average Duration:", round(Avg_Duration_Hours, 1), "hours", 
                      "<br>Minutes:", round(Avg_Duration_Min, 0),
                      "<br>Sample Size:", Count)) %>%
  layout(
    title = "Average Sleep Duration by Day of Week",
    xaxis = list(title = "Day of Week"),
    yaxis = list(title = "Sleep Duration (hours)", range = c(0, 8)),
    hovermode = "closest"
  )
```


### Weekday vs Weekend Sleep Comparison {data-width=900}

```{r}
# Calculate averages for weekday vs weekend
sleep_weekday_weekend <- sleep_data %>%
  mutate(Is_Weekend = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday")) %>%
  group_by(Is_Weekend) %>%
  summarize(
    Avg_Duration = mean(`Total Sleep Duration (min)`),
    Avg_Duration_Hours = Avg_Duration / 60,
    SD_Duration = sd(`Total Sleep Duration (min)`),
    Count = n()
  )

# Create interactive bar chart for weekday vs weekend comparison
plot_ly(sleep_weekday_weekend, x = ~Is_Weekend, y = ~Avg_Duration, type = 'bar',
        error_y = list(type = 'data', array = ~SD_Duration, visible = TRUE),
        marker = list(color = c("#69b3a2", "#404080")),
        text = ~paste("Type:", Is_Weekend, 
                      "<br>Average Duration:", round(Avg_Duration, 1), "min", 
                      "<br>Average Hours:", round(Avg_Duration_Hours, 1),
                      "<br>Sample Size:", Count)) %>%
  layout(
    title = "Average Sleep Duration: Weekday vs Weekend",
    xaxis = list(title = ""),
    yaxis = list(title = "Sleep Duration (minutes)"),
    hovermode = "closest"
  )
```


### Sleep Duration Trends Over Time {data-width=900}

```{r}
# Prepare data for time series visualization
sleep_time_series <- sleep_data %>%
  arrange(Date) %>%
  mutate(
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday"),
    Duration_Hours = `Total Sleep Duration (min)` / 60
  )

# Create interactive time series visualization
plot_ly(sleep_time_series, x = ~Date, y = ~Duration_Hours, 
        type = 'scatter', mode = 'lines+markers',
        color = ~Day_Type,
        marker = list(size = 8),
        text = ~paste("Date:", Date, 
                     "<br>Day:", Day_of_Week,
                     "<br>Hours:", round(Duration_Hours, 1),
                     "<br>Minutes:", `Total Sleep Duration (min)`)) %>%
  layout(
    title = "Sleep Duration Trend Over Time",
    xaxis = list(title = "Date"),
    yaxis = list(title = "Sleep Duration (hours)", range = c(4, 8)),
    hovermode = "closest"
  ) %>%
  add_lines(y = ~mean(Duration_Hours), name = "Average", 
            line = list(color = 'red', dash = 'dash'))
```

# **Sleep Quality Analysis**

Row {data-height=180}
------------------------

### **Overview of Sleep Quality Patterns**

The dataset from **Samsung Health** provides comprehensive metrics not only for sleep duration but also for sleep quality. Sleep quality measures include the Sleep Score, Sleep Efficiency (%), and time spent in different sleep stages. While duration focuses on quantity, quality metrics offer insights into the restorative nature of sleep.

This analysis explores sleep quality from three key perspectives:

- **Quality by day of week**: How sleep quality scores vary across different days
- **Bedtime vs sleep quality**: The relationship between when sleep begins and its overall quality
- **Sleep efficiency patterns**: How effectively sleep time is utilized throughout the week

Understanding these quality dimensions complements duration analysis and provides a more complete picture of sleep health, potentially revealing factors that affect sleep beyond simple duration measures.

Row {.tabset .tabset-fade data-width=550}
------------------------

### **Quality by Day of Week**
```{r}
# Calculate average sleep quality by day of week
sleep_quality_by_day <- sleep_data %>%
  mutate(Day_of_Week = factor(Day_of_Week, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))) %>%
  group_by(Day_of_Week) %>%
  summarize(
    Avg_Quality = mean(`Sleep Score`),
    SD_Quality = sd(`Sleep Score`),
    Avg_Efficiency = mean(`Sleep Efficiency (%)`),
    Count = n()
  )

# Create interactive bar chart for sleep quality by day of week
plot_ly(sleep_quality_by_day, x = ~Day_of_Week, y = ~Avg_Quality, type = 'bar',
        error_y = list(type = 'data', array = ~SD_Quality, visible = TRUE),
        marker = list(color = viridis(7, alpha = 0.8, option = "D")),
        text = ~paste("Day:", Day_of_Week, 
                      "<br>Average Sleep Score:", round(Avg_Quality, 1),
                      "<br>Sleep Efficiency:", round(Avg_Efficiency, 1), "%",
                      "<br>Sample Size:", Count)) %>%
  layout(
    title = "Average Sleep Quality by Day of Week",
    xaxis = list(title = "Day of Week"),
    yaxis = list(title = "Sleep Score (0-100)", range = c(0, 100)),
    hovermode = "closest"
  )
```

### **Bedtime vs Sleep Quality** {data-width=900}

```{r}
# Extract bedtime hour from Start Time
sleep_bedtime <- sleep_data %>%
  mutate(
    Start_Time_Clean = as.POSIXct(paste("2025-01-01", `Start Time`), format = "%Y-%m-%d %H:%M", tz = "UTC"),
    Bedtime_Hour = as.numeric(format(Start_Time_Clean, "%H")) + 
                   as.numeric(format(Start_Time_Clean, "%M"))/60,
    Bedtime_Hour = ifelse(Bedtime_Hour < 12, Bedtime_Hour + 24, Bedtime_Hour)
  )

# Create scatter plot of bedtime vs sleep quality
plot_ly(sleep_bedtime, x = ~Bedtime_Hour, y = ~`Sleep Score`, 
        type = 'scatter', mode = 'markers',
        marker = list(
          color = ~`Sleep Score`,
          colorscale = 'Viridis',
          colorbar = list(title = "Sleep Score"),
          size = 10, 
          opacity = 0.7
        ),
        showlegend = FALSE,
        text = ~paste("Date:", Date, 
                     "<br>Bedtime:", `Start Time`,
                     "<br>Sleep Score:", `Sleep Score`,
                     "<br>Sleep Duration:", round(`Total Sleep Duration (min)`/60, 1), "hours")) %>%
  layout(
    title = "Relationship Between Bedtime and Sleep Quality",
    xaxis = list(title = "Bedtime (24-hour format)", 
                 tickvals = c(20, 21, 22, 23, 24, 25, 26, 27, 28),
                 ticktext = c("8 PM", "9 PM", "10 PM", "11 PM", "12 AM", "1 AM", "2 AM", "3 AM", "4 AM")),
    yaxis = list(title = "Sleep Score (0-100)"),
    hovermode = "closest"
  ) %>%
  add_lines(x = ~Bedtime_Hour, y = ~fitted(loess(`Sleep Score` ~ Bedtime_Hour)), 
            line = list(color = 'red', width = 2), 
            name = "Trend",
            showlegend = FALSE)
```

### **Sleep Efficiency Patterns** {data-width=900}

```{r}
# Create time series for sleep efficiency
sleep_efficiency_series <- sleep_data %>%
  arrange(Date) %>%
  mutate(
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday")
  )

# Create interactive visualization for sleep efficiency over time
plot_ly(sleep_efficiency_series, x = ~Date, y = ~`Sleep Efficiency (%)`, 
        type = 'scatter', mode = 'lines+markers',
        color = ~Day_Type,
        marker = list(size = 8),
        text = ~paste("Date:", Date, 
                     "<br>Day:", Day_of_Week,
                     "<br>Sleep Efficiency:", round(`Sleep Efficiency (%)`, 1), "%",
                     "<br>Sleep Score:", `Sleep Score`,
                     "<br>Total Sleep:", round(`Total Sleep Duration (min)`/60, 1), "hours")) %>%
  layout(
    title = "Sleep Efficiency Trend Over Time",
    xaxis = list(title = "Date"),
    yaxis = list(title = "Sleep Efficiency (%)", range = c(75, 100)),
    hovermode = "closest"
  ) %>%
  add_lines(y = ~mean(`Sleep Efficiency (%)`), name = "Average", 
            line = list(color = 'red', dash = 'dash'))
```


# **Sleep Composition Analysis**

Row {data-height=180}
------------------------

### **Overview of Sleep Composition Patterns**

Sleep composition refers to the different stages of sleep experienced throughout the night. The **Samsung Health** data captures three primary sleep stages: **REM** (Rapid Eye Movement), **Light**, and **Deep** sleep, as well as time spent **Awake**. These stages are crucial indicators of sleep quality and restorative value.

REM sleep is associated with dreaming and memory consolidation, while deep sleep provides the most restorative benefits. Light sleep serves as a transition between other stages. The ideal sleep composition varies by age, but for adults, a healthy distribution typically includes 20-25% REM, 50-60% light, and 15-25% deep sleep.

This analysis examines sleep composition from two perspectives:
- **Sleep stages distribution**: The breakdown of time spent in each sleep stage
- **Comparison across different periods**: How sleep composition varies between weekdays and weekends

Understanding sleep stage composition can provide insights into sleep quality beyond duration and efficiency metrics, potentially revealing factors affecting overall sleep health.

Row {.tabset .tabset-fade data-width=550}
------------------------

### **Sleep Stages Distribution**
```{r}
# Calculate average time in each sleep stage
sleep_stages_avg <- sleep_data %>%
  summarize(
    REM = mean(`REM Sleep (min)`),
    Light = mean(`Light Sleep (min)`),
    Deep = mean(`Deep Sleep (min)`),
    Awake = mean(`Awake Duration (min)`)
  ) %>%
  pivot_longer(cols = everything(), names_to = "Stage", values_to = "Duration") %>%
  mutate(
    Percentage = Duration / sum(Duration) * 100,
    Stage = factor(Stage, levels = c("Deep", "Light", "REM", "Awake"))
  )

# Create pie chart for sleep stages distribution
plot_ly(sleep_stages_avg, labels = ~Stage, values = ~Duration, type = 'pie',
        textposition = 'inside',
        textinfo = 'label+percent',
        insidetextfont = list(color = '#FFFFFF'),
        hoverinfo = 'text',
        text = ~paste(Stage, "Sleep:", 
                     "<br>Minutes:", round(Duration, 1),
                     "<br>Hours:", round(Duration/60, 1),
                     "<br>Percentage:", round(Percentage, 1), "%"),
        marker = list(colors = c("#355C7D", "#6C5B7B", "#C06C84", "#F8B195"),
                     line = list(color = '#FFFFFF', width = 1))) %>%
  layout(
    title = "Sleep Stages Distribution (Average)",
    showlegend = TRUE,
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.1)
  )
```

### **Comparison of Sleep Stages** {data-width=900}

```{r}
# Calculate sleep stages by weekday/weekend
sleep_stages_comparison <- sleep_data %>%
  mutate(Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday")) %>%
  group_by(Day_Type) %>%
  summarize(
    REM = mean(`REM Sleep (min)`),
    Light = mean(`Light Sleep (min)`),
    Deep = mean(`Deep Sleep (min)`),
    Awake = mean(`Awake Duration (min)`),
    Total = REM + Light + Deep,
    REM_Pct = REM / Total * 100,
    Light_Pct = Light / Total * 100,
    Deep_Pct = Deep / Total * 100
  ) %>%
  pivot_longer(cols = c(REM, Light, Deep, Awake), names_to = "Stage", values_to = "Duration") %>%
  mutate(
    Stage = factor(Stage, levels = c("Deep", "Light", "REM", "Awake"))
  )

# Create grouped bar chart for weekday vs weekend sleep stages
plot_ly(sleep_stages_comparison, x = ~Day_Type, y = ~Duration, color = ~Stage, type = 'bar',
        colors = c("#355C7D", "#6C5B7B", "#C06C84", "#F8B195"),
        text = ~paste(Stage, ":", round(Duration, 1), "min")) %>%
  layout(
    title = "Sleep Stages: Weekday vs Weekend",
    xaxis = list(title = ""),
    yaxis = list(title = "Duration (minutes)"),
    barmode = 'stack',
    hovermode = "closest",
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.1)
  )
```

### **Sleep Stages Over Time** {data-width=900}

```{r}
# Prepare data for time series of sleep stages
sleep_stages_time <- sleep_data %>%
  arrange(Date) %>%
  mutate(
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday"),
    Deep_Pct = `Deep Sleep (min)` / `Total Sleep Duration (min)` * 100,
    Light_Pct = `Light Sleep (min)` / `Total Sleep Duration (min)` * 100,
    REM_Pct = `REM Sleep (min)` / `Total Sleep Duration (min)` * 100
  )

# Create area chart for sleep stage percentages over time
plot_ly(sleep_stages_time, x = ~Date) %>%
  add_trace(y = ~Deep_Pct, name = 'Deep', type = 'scatter', mode = 'lines', 
            stackgroup = 'one', fillcolor = '#355C7D',
            line = list(width = 0.5),
            hoverinfo = "text",
            text = ~paste("Date:", Date, 
                         "<br>Deep Sleep:", round(Deep_Pct, 1), "%",
                         "<br>Minutes:", `Deep Sleep (min)`)) %>%
  add_trace(y = ~Light_Pct, name = 'Light', type = 'scatter', mode = 'lines', 
            stackgroup = 'one', fillcolor = '#6C5B7B',
            line = list(width = 0.5),
            hoverinfo = "text",
            text = ~paste("Date:", Date, 
                         "<br>Light Sleep:", round(Light_Pct, 1), "%",
                         "<br>Minutes:", `Light Sleep (min)`)) %>%
  add_trace(y = ~REM_Pct, name = 'REM', type = 'scatter', mode = 'lines', 
            stackgroup = 'one', fillcolor = '#C06C84',
            line = list(width = 0.5),
            hoverinfo = "text",
            text = ~paste("Date:", Date, 
                         "<br>REM Sleep:", round(REM_Pct, 1), "%",
                         "<br>Minutes:", `REM Sleep (min)`)) %>%
  layout(
    title = "Sleep Composition Over Time (% of Total Sleep)",
    xaxis = list(title = "Date"),
    yaxis = list(title = "Percentage of Total Sleep", range = c(0, 100)),
    hovermode = "closest",
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.1)
  )
```

# **Sleep Consistency Analysis**

Row {data-height=180}
------------------------

### **Overview of Sleep Consistency Patterns**

Sleep consistency refers to the regularity of sleep patterns over time, including consistent bedtimes, wake times, and total sleep duration. Research suggests that maintaining regular sleep patterns may be as important as sleep duration for overall health and wellbeing. Irregular sleep patterns have been associated with poorer health outcomes including increased risk of cardiovascular disease, metabolic disorders, and mood disturbances.

The **Samsung Health** data allows for detailed analysis of sleep consistency through metrics such as bedtime variability and sleep duration fluctuations. This analysis examines sleep consistency from two key perspectives:

- **Bedtime consistency**: How regular bedtime patterns are across days of the week
- **Sleep duration variability**: How much total sleep time fluctuates over the collection period

Understanding these patterns can reveal opportunities to improve sleep hygiene practices and potentially enhance overall sleep quality and health outcomes.

Row {.tabset .tabset-fade data-width=550}
------------------------

### **Bedtime Consistency**
```{r}
# Extract bedtime hour and prepare for heatmap
sleep_bedtime_consistency <- sleep_data %>%
  mutate(
    Start_Time_Clean = as.POSIXct(paste("2025-01-01", `Start Time`), format = "%Y-%m-%d %H:%M", tz = "UTC"),
    Bedtime_Hour = as.numeric(format(Start_Time_Clean, "%H")) + 
                   as.numeric(format(Start_Time_Clean, "%M"))/60,
    Bedtime_Hour = ifelse(Bedtime_Hour < 12, Bedtime_Hour + 24, Bedtime_Hour),
    Hour_Range = cut(Bedtime_Hour, 
                     breaks = seq(20, 32, by = 1),
                     labels = c("8-9 PM", "9-10 PM", "10-11 PM", "11PM-12AM", 
                                "12-1 AM", "1-2 AM", "2-3 AM", "3-4 AM", 
                                "4-5 AM", "5-6 AM", "6-7 AM", "7-8 AM"),
                     include.lowest = TRUE)
  )

bedtime_counts <- sleep_bedtime_consistency %>%
  count(Day_of_Week, Hour_Range) %>%
  mutate(Day_of_Week = factor(Day_of_Week, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")))

# Create heatmap for bedtime consistency
plot_ly(bedtime_counts, x = ~Hour_Range, y = ~Day_of_Week, z = ~n, type = "heatmap",
        colorscale = "Viridis",
        text = ~paste("Day:", Day_of_Week, 
                     "<br>Time:", Hour_Range,
                     "<br>Count:", n),
        hoverinfo = "text") %>%
  layout(
    title = "Bedtime Consistency Across Days of Week",
    xaxis = list(title = "Bedtime Hour", tickangle = 45),
    yaxis = list(title = "", autorange = "reversed"),
    coloraxis = list(colorbar = list(title = "Frequency"))
  )
```

### **Sleep Duration Variability** {data-width=900}

```{r}
# Calculate sleep duration statistics
sleep_duration_stats <- sleep_data %>%
  summarize(
    Mean_Duration = mean(`Total Sleep Duration (min)`),
    Median_Duration = median(`Total Sleep Duration (min)`),
    SD_Duration = sd(`Total Sleep Duration (min)`),
    CV_Duration = SD_Duration / Mean_Duration * 100,  # Coefficient of variation
    Min_Duration = min(`Total Sleep Duration (min)`),
    Max_Duration = max(`Total Sleep Duration (min)`),
    Range_Duration = Max_Duration - Min_Duration,
    IQR_Duration = IQR(`Total Sleep Duration (min)`)
  ) %>%
  mutate(
    Mean_Hours = Mean_Duration / 60,
    Median_Hours = Median_Duration / 60,
    SD_Hours = SD_Duration / 60,
    Min_Hours = Min_Duration / 60,
    Max_Hours = Max_Duration / 60,
    Range_Hours = Range_Duration / 60,
    IQR_Hours = IQR_Duration / 60
  )

sleep_duration_hist <- sleep_data %>%
  mutate(
    Duration_Hours = `Total Sleep Duration (min)` / 60,
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday")
  )

# Create histogram of sleep duration distribution
plot_ly(sleep_duration_hist, x = ~Duration_Hours, type = "histogram", 
        color = ~Day_Type,
        colors = c("#69b3a2", "#404080"),
        nbinsx = 12,
        opacity = 0.7) %>%
  layout(
    title = "Distribution of Sleep Duration",
    xaxis = list(title = "Sleep Duration (hours)", range = c(4, 9)),
    yaxis = list(title = "Frequency"),
    barmode = "overlay",
    bargap = 0.1,
    annotations = list(
      list(
        x = sleep_duration_stats$Mean_Hours,
        y = 0,
        text = paste("Mean:", round(sleep_duration_stats$Mean_Hours, 1), "h"),
        showarrow = TRUE,
        arrowhead = 2,
        ax = 0,
        ay = -40
      ),
      list(
        x = sleep_duration_stats$Mean_Hours - sleep_duration_stats$SD_Hours,
        y = 0,
        text = "-1 SD",
        showarrow = TRUE,
        arrowhead = 2,
        ax = 0,
        ay = -20
      ),
      list(
        x = sleep_duration_stats$Mean_Hours + sleep_duration_stats$SD_Hours,
        y = 0,
        text = "+1 SD",
        showarrow = TRUE,
        arrowhead = 2,
        ax = 0,
        ay = -20
      )
    )
  )
```

### **Consistency Metrics** {data-width=900}

```{r}
# Calculate day-to-day variability
sleep_day_variability <- sleep_data %>%
  arrange(Date) %>%
  mutate(
    Next_Duration = lead(`Total Sleep Duration (min)`),
    Daily_Change = abs(Next_Duration - `Total Sleep Duration (min)`),
    Daily_Change_Hours = Daily_Change / 60,
    Change_Category = cut(Daily_Change_Hours, 
                          breaks = c(0, 0.5, 1, 1.5, 2, 3, Inf),
                          labels = c("<30min", "30-60min", "1-1.5h", "1.5-2h", "2-3h", ">3h"),
                          include.lowest = TRUE)
  ) %>%
  filter(!is.na(Daily_Change))

# Create a line chart showing day-to-day variability
plot_ly(sleep_day_variability, x = ~Date, y = ~Daily_Change_Hours, type = "scatter", mode = "lines+markers",
        marker = list(
          color = ~Daily_Change_Hours,
          colorscale = "Viridis",
          size = 10
        ),
        line = list(color = '#69b3a2'),
        text = ~paste("Date:", Date, 
                     "<br>Variation from previous day:", round(Daily_Change_Hours, 1), "hours",
                     "<br>Current sleep:", round(`Total Sleep Duration (min)`/60, 1), "hours",
                     "<br>Previous sleep:", round(lead(`Total Sleep Duration (min)`)/60, 1), "hours")) %>%
  layout(
    title = "Day-to-Day Sleep Duration Variability",
    xaxis = list(title = "Date"),
    yaxis = list(title = "Change from Previous Day (hours)", range = c(0, 3)),
    hovermode = "closest"
  ) %>%
  add_lines(y = mean(sleep_day_variability$Daily_Change_Hours), name = "Average Variability", 
            line = list(color = 'red', dash = 'dash'))
```


# **Interactive Sleep Exploration**

Row {data-height=180}
------------------------

### **Interactive Sleep Data Analysis**

The interactive exploration section allows for dynamic analysis of sleep patterns across different metrics. Plotly's built-in controls enable filtering, zooming, and hovering to explore specific data points of interest. The visualizations below provide three complementary perspectives:

1. **Sleep metrics across days of week**: Compare how key sleep metrics vary across different days
2. **Sleep metric correlations**: Examine relationships between different sleep parameters
3. **Sleep pattern trends over time**: Track how sleep patterns have evolved throughout the data collection period

These interactive visualizations allow for deeper insights beyond the static analyses in previous sections, helping to identify potential factors influencing sleep quality and patterns.

Row {.tabset .tabset-fade data-height=550}
------------------------

### **Sleep Metrics by Day of Week** {data-width=900}

```{r}
# Create a more flexible day of week comparison
metrics_by_day <- sleep_data %>%
  mutate(Day_of_Week = factor(Day_of_Week, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))) %>%
  group_by(Day_of_Week) %>%
  summarize(
    Duration = mean(`Total Sleep Duration (min)`)/60,
    Score = mean(`Sleep Score`),
    Efficiency = mean(`Sleep Efficiency (%)`),
    REM = mean(`REM Sleep (min)`)/60,
    Deep = mean(`Deep Sleep (min)`)/60,
    Light = mean(`Light Sleep (min)`)/60,
    Count = n()
  )

# Create interactive bar chart with metric dropdown selector
plot_ly(metrics_by_day) %>%
  add_trace(
    x = ~Day_of_Week,
    y = ~Duration,
    type = 'bar',
    name = 'Sleep Duration (hours)',
    visible = TRUE,
    marker = list(color = viridis(7, alpha = 0.8))
  ) %>%
  add_trace(
    x = ~Day_of_Week,
    y = ~Score,
    type = 'bar',
    name = 'Sleep Score',
    visible = 'legendonly',
    marker = list(color = viridis(7, alpha = 0.8, option = "B"))
  ) %>%
  add_trace(
    x = ~Day_of_Week,
    y = ~Efficiency,
    type = 'bar',
    name = 'Sleep Efficiency (%)',
    visible = 'legendonly',
    marker = list(color = viridis(7, alpha = 0.8, option = "C"))
  ) %>%
  add_trace(
    x = ~Day_of_Week,
    y = ~Deep,
    type = 'bar',
    name = 'Deep Sleep (hours)',
    visible = 'legendonly',
    marker = list(color = viridis(7, alpha = 0.8, option = "D"))
  ) %>%
  add_trace(
    x = ~Day_of_Week,
    y = ~REM,
    type = 'bar',
    name = 'REM Sleep (hours)',
    visible = 'legendonly',
    marker = list(color = viridis(7, alpha = 0.8, option = "E"))
  ) %>%
  layout(
    title = "Sleep Metrics by Day of Week (Click Legend to Toggle Metrics)",
    xaxis = list(title = "Day of Week"),
    yaxis = list(title = "Value"),
    barmode = 'group',
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.2),
    updatemenus = list(
      list(
        buttons = list(
          list(method = "update", 
               args = list(list(visible = c(TRUE, FALSE, FALSE, FALSE, FALSE)),
                         list(yaxis = list(title = "Sleep Duration (hours)"))),
               label = "Duration"),
          list(method = "update", 
               args = list(list(visible = c(FALSE, TRUE, FALSE, FALSE, FALSE)),
                         list(yaxis = list(title = "Sleep Score"))),
               label = "Score"),
          list(method = "update", 
               args = list(list(visible = c(FALSE, FALSE, TRUE, FALSE, FALSE)),
                         list(yaxis = list(title = "Sleep Efficiency (%)"))),
               label = "Efficiency"),
          list(method = "update", 
               args = list(list(visible = c(FALSE, FALSE, FALSE, TRUE, FALSE)),
                         list(yaxis = list(title = "Deep Sleep (hours)"))),
               label = "Deep Sleep"),
          list(method = "update", 
               args = list(list(visible = c(FALSE, FALSE, FALSE, FALSE, TRUE)),
                         list(yaxis = list(title = "REM Sleep (hours)"))),
               label = "REM Sleep")
        ),
        direction = "down",
        showactive = TRUE,
        x = 0.1,
        xanchor = "left",
        y = 1.15,
        yanchor = "top"
      )
    )
  )
```

### **Sleep Metric Correlations** {data-width=900}

```{r}
# Create data for scatter plot with multiple metrics
sleep_correlations <- sleep_data %>%
  select(`Total Sleep Duration (min)`, `Sleep Score`, `Sleep Efficiency (%)`, 
         `REM Sleep (min)`, `Deep Sleep (min)`, `Light Sleep (min)`, 
         `Awake Duration (min)`, Day_of_Week) %>%
  mutate(
    Duration_Hours = `Total Sleep Duration (min)` / 60,
    REM_Hours = `REM Sleep (min)` / 60,
    Deep_Hours = `Deep Sleep (min)` / 60,
    Light_Hours = `Light Sleep (min)` / 60,
    Awake_Hours = `Awake Duration (min)` / 60,
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday")
  )

# Create interactive scatter plot
plot_ly(sleep_correlations, x = ~Duration_Hours, y = ~`Sleep Score`, 
        color = ~Day_Type, 
        colors = c("#69b3a2", "#404080"),
        type = 'scatter', mode = 'markers',
        marker = list(size = 10, opacity = 0.7),
        text = ~paste("Day:", Day_of_Week, 
                     "<br>Duration:", round(Duration_Hours, 1), "hours",
                     "<br>Sleep Score:", `Sleep Score`,
                     "<br>Efficiency:", round(`Sleep Efficiency (%)`, 1), "%")) %>%
  layout(
    title = "Relationship Between Sleep Metrics (Use Dropdown to Change)",
    xaxis = list(title = "Sleep Duration (hours)"),
    yaxis = list(title = "Sleep Score"),
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.2),
    updatemenus = list(
      list(
        buttons = list(
          list(method = "update", 
               args = list(list(x = list(sleep_correlations$Duration_Hours), 
                              y = list(sleep_correlations$`Sleep Score`)),
                         list(xaxis = list(title = "Sleep Duration (hours)"),
                              yaxis = list(title = "Sleep Score"))),
               label = "Duration vs Score"),
          list(method = "update", 
               args = list(list(x = list(sleep_correlations$Duration_Hours), 
                              y = list(sleep_correlations$`Sleep Efficiency (%)`)),
                         list(xaxis = list(title = "Sleep Duration (hours)"),
                              yaxis = list(title = "Sleep Efficiency (%)"))),
               label = "Duration vs Efficiency"),
          list(method = "update", 
               args = list(list(x = list(sleep_correlations$Deep_Hours), 
                              y = list(sleep_correlations$`Sleep Score`)),
                         list(xaxis = list(title = "Deep Sleep (hours)"),
                              yaxis = list(title = "Sleep Score"))),
               label = "Deep Sleep vs Score"),
          list(method = "update", 
               args = list(list(x = list(sleep_correlations$REM_Hours), 
                              y = list(sleep_correlations$`Sleep Score`)),
                         list(xaxis = list(title = "REM Sleep (hours)"),
                              yaxis = list(title = "Sleep Score"))),
               label = "REM Sleep vs Score")
        ),
        direction = "down",
        showactive = TRUE,
        x = 0.1,
        xanchor = "left",
        y = 1.15,
        yanchor = "top"
      )
    )
  )
```

### **Sleep Trends Over Time** {data-width=900}

```{r}
# Create time series data
sleep_time_trends <- sleep_data %>%
  arrange(Date) %>%
  mutate(
    Day_Type = ifelse(Day_of_Week %in% c("Saturday", "Sunday"), "Weekend", "Weekday"),
    Duration_Hours = `Total Sleep Duration (min)` / 60,
    Rolling_Avg = zoo::rollmean(Duration_Hours, k = 7, fill = NA, align = "right")
  )

# Create interactive time series plot
plot_ly(sleep_time_trends) %>%
  add_trace(
    x = ~Date, 
    y = ~Duration_Hours, 
    type = 'scatter', 
    mode = 'markers+lines',
    name = 'Daily Duration',
    connectgaps = FALSE,
    color = ~Day_Type,
    colors = c("#69b3a2", "#404080"),
    marker = list(size = 8),
    text = ~paste("Date:", Date, 
                 "<br>Day:", Day_of_Week,
                 "<br>Duration:", round(Duration_Hours, 1), "hours")
  ) %>%
  add_trace(
    x = ~Date, 
    y = ~Rolling_Avg, 
    type = 'scatter', 
    mode = 'lines',
    name = '7-Day Average',
    line = list(color = 'red', width = 3, dash = 'solid'),
    visible = TRUE
  ) %>%
  add_trace(
    x = ~Date, 
    y = ~`Sleep Score`, 
    type = 'scatter', 
    mode = 'lines',
    name = 'Sleep Score',
    yaxis = "y2",
    line = list(color = 'purple', width = 2),
    visible = "legendonly"
  ) %>%
  layout(
    title = "Sleep Patterns Over Time",
    xaxis = list(title = "Date"),
    yaxis = list(title = "Sleep Duration (hours)", side = "left"),
    yaxis2 = list(title = "Sleep Score", side = "right", overlaying = "y", showgrid = FALSE),
    legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.2),
    hovermode = "closest"
  )
```

# **Conclusions & Optimization Strategy**

Row {data-height=350}
------------------------

### **Summary of Sleep Pattern Analysis**

The comprehensive analysis of sleep data from Samsung Health has provided valuable insights into sleep patterns across duration, quality, composition, and consistency dimensions. These insights can inform targeted interventions to improve overall sleep health.

| **Key Finding**  | **Description** | **Optimization Strategy** |
|:-----------------|:----------------|:-------------------|
| **Duration Deficit** | Average sleep duration (6.5 hours) consistently falls below the recommended 7-9 hours for adults, with Sunday showing the lowest duration (5.9 hours). | Aim to extend sleep duration by 30-60 minutes, with particular focus on Sunday nights. Consider establishing an earlier bedtime routine on Sundays to prepare for the work week. |
| **Weekday-Weekend Inversion** | Contrary to typical patterns, weekday sleep (6.6 hours) exceeds weekend sleep (6.3 hours), suggesting inadequate recovery sleep during weekends. | Prioritize consistent sleep duration through the entire week, avoiding the temptation to dramatically shift weekend sleep patterns. If social obligations affect weekend sleep, consider compensatory naps when possible. |
| **Bedtime Impact on Quality** | Earlier bedtimes (before 11 PM) correlate with higher sleep quality scores, with quality declining for bedtimes after midnight. | Establish a consistent sleep schedule with target bedtime before 11 PM when possible. Create a wind-down routine 30-60 minutes before bedtime to facilitate falling asleep earlier. |
| **Deep Sleep Abundance** | Sleep composition shows higher-than-average deep sleep (46%) with somewhat lower REM sleep (15%), which may affect cognitive functions. | While the abundance of deep sleep is positive for physical recovery, strategies to improve REM sleep might include: reducing alcohol consumption, managing stress, and ensuring adequate total sleep time to allow for complete sleep cycles. |
| **Schedule Irregularity** | Significant bedtime variability (2-3 hour range) and moderate duration variability (SD = 30 min) indicate inconsistent sleep patterns that may reduce overall sleep quality. | Aim to maintain consistent sleep and wake times within a 30-minute window, even on weekends. Use a sleep tracking app with bedtime reminders to establish regularity in the sleep-wake cycle. |