Overview

Final Project for ANLY512: Data Visualization

The Quantified Self

  • Data Source: My Mobile Phone
  • Data Type: Health Data - Steps, Walking + Running Distance, Flights Climbed
  • Data Time Range: December 2022 to November 2023
  • Data Frequency: Daily

The goal of this project is to collect, analyze and visualize my daily activity data using R programming language and analytical methods covered by this course. Using the data-driven approaches, I put forward following five questions based on my data collected:

  1. Q1: How many steps/how far did I walk every day on average in each month?
  2. Q2: How many floors did I climb every day?
  3. Q3: Did I go out more on weekends than weekdays?
  4. Q4: Which season was my favorite time for outdoor walking?
  5. Q5: What is the trend for my daily steps?

Before delving into the visualization and analysis sections, I’d like to provide some context about the dataset. This collection records a series of my outdoor activities, encompassing daily step counts, walking distances, and flights climbed (a detailed description of the dataset will be covered in the subsequent section). The data were retrieved from my iPhone Health App.

Unlike dedicated outdoor runners who might utilize this health app data to analyze their running patterns, I consider this dataset a record of my walking activities. This is because I usually exercise in the gym without my device, resulting in no recorded workout information within this dataset.

This statement underscores the value of this dataset. In New York City, walking stands as a routine daily activity amidst various social engagements like commuting, shopping, socializing with friends, and increasingly, leisurely strolls within the city.”

The latter analysis was conducted based on above background.

Data preparation

Sample raw data
Date Distance_mi ElevationGain_m Steps
12-1-2022 3.60 1 7685
12-2-2022 2.90 2 6644
12-3-2022 1.50 2 3364
12-4-2022 4.00 9 9210
12-5-2022 3.40 6 7944
12-6-2022 5.10 3 11253
12-7-2022 1.80 1 4129
12-8-2022 5.30 11 11972
12-9-2022 3.30 6 7635
12-10-2022 0.92 1 2212
12-11-2022 1.30 3 3042
12-12-2022 3.00 9 6741
12-13-2022 3.40 4 7736
12-14-2022 6.60 7 14800
12-15-2022 1.90 4 4309

Definition of variables

Q1: How many steps/how far did I walk every day in each month?


I was aiming to compare the average walking steps and distance I took in each month. Since “Month” is a categorical variable, Steps and Distance are continuous variables, histogram and line chart were chosen for visualization purpose. I combined histogram for “steps” added with lines displaying “distance” information to make a concise summary of the two varaibles. X-axis is month, and Y-axis are steps and distance.

The graph illustrates a notable similarity in the patterns between steps and distance throughout the months. This correlation is expected as these variables are strongly correlated - an increase in my daily steps corresponds to an increase in the total walking distance.

From the plot, on average I walked around 8,700 steps and 3.75 miles every day, however, the average numbers vary from one month to another.

Q2: How many floors did I climb every day?


Since I was more interested to take a look at the overall of my climbing activity, Pie chart was applied to simply and intuitively display the relative proportions of the climbed data.

The pie chart illustrates that my daily climbing typically ranged from 0 to 6 floors. It’s important to note that this data captures movements while I had my phone, excluding instances when I used the stairs machine at the gym. Moreover, I have elevator access in my residential and office buildings, minimizing stair usage at home or the office. Thus, this climbing activity occurred inadvertently.

Q3: Do I go out more on weekends than weekdays?


A box plot is a visual tool used in statistics to understand the distribution of a dataset and identify characteristics such as central tendency, dispersion, and skewness. It provides a graphical representation of the five-number summary: minimum, first quartile (Q1), median (second quartile, Q2), third quartile (Q3), and maximum.

The box plot effectively addresses this inquiry. The plot reveals a wider range in my outdoor activities on weekends compared to weekdays, signifying greater variability in weekend events influenced, most probably, by my mood. Weekends often reflect flexibility—some days I may feel “LAZY” - inclined to relax indoors, while others spur excitement for outdoor ventures. Consequently, the majority of my weekend daily step distributions fall within the range of 6150 to 13690, with a median of 9406.

In contrast, my weekday steps exhibit more stability, showcasing a symmetric distribution spanning 6848 to 9343, with a median value of 8080. Although I might adopt a more relaxed approach over the weekend, I appear to maintain relatively higher activity levels compared to weekdays, with a few days showing considerably higher step counts, leading to the upper bound values in the box chart.

Drawing a conclusive statement about my weekend versus weekday outdoor activity based solely on step counts seems challenging. However, it’s noticeable that on weekends, when I am outdoors instead of staying home, I tend to engage in longer and more extensive walks compared to weekdays.

Q4: Which season is my favorite season for outdoor walking?


In analyzing the data, it’s evident that autumn records the highest daily average steps, indicating my preference for outdoor activities during this season. Surprisingly, contrary to common trends, my steps during summer are notably lower compared to other times. This discrepancy is attributed to my avoidance of extreme temperatures; consequently, I tend to stay indoors or engage in gym workouts during the hotter summer months.

Q5:What’s the trend for my daily steps?


Here I did a time series analysis for daily steps by using ARIMA model to forecast the next 30 days of steps data. In my model, I considered several effects to forecast future steps: Trend (AR term), Seasonality (MA term), and Stationarity (Integrated term).

A time series plot was used to showcase the forecasted steps for future dates based on historical data, highlighting the trend and potential variations expected in the steps taken over the next 30 days.

The time series plot depicting daily data shows significant fluctuations within the dataset. In earlier analyses, I aggregated the step data on a monthly or seasonal basis, creating a smoother pattern. This new view reveals extreme values in several months (September, October, and November). I recalled during those months I went on hiking and city walks, enjoying the good weather as well as appreciating maple leaves.

Based on the historical steps data, in the following month, which is December 2023, I will take on average, 9376 steps per day.

---
title: "ANLY 512 Final Project"
author: "Minzhi Meng"
date: "Dec 8, 2023"
output: 
  flexdashboard::flex_dashboard:
    storyboard: true
    social: menu
    source: embed
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(flexdashboard)
library(knitr)
library(ggplot2)
library(tidyverse)
library(readxl)
library(dplyr)
library(xts)
library(zoo)
library(lubridate) 
library(plotly)
library(shiny)

```
### Overview

#####
**Final Project for ANLY512: Data Visualization**

**The Quantified Self**

 * Data Source: **My Mobile Phone**
 * Data Type: **Health Data - Steps, Walking + Running Distance, Flights Climbed**
 * Data Time Range: **December 2022 to November 2023**
 * Data Frequency: **Daily**
 

The goal of this project is to collect, analyze and visualize my daily activity data using R programming language and analytical methods covered by this course. Using the data-driven approaches, I put forward following five questions based on my data collected:

1) Q1: How many steps/how far did I walk every day on average in each month?
2) Q2: How many floors did I climb every day?
3) Q3: Did I go out more on weekends than weekdays?
4) Q4: Which season was my favorite time for outdoor walking? 
5) Q5: What is the trend for my daily steps? 


Before delving into the visualization and analysis sections, I'd like to provide some context about the dataset. This collection records a series of my outdoor activities, encompassing daily step counts, walking distances, and flights climbed (a detailed description of the dataset will be covered in the subsequent section). The data were retrieved from my iPhone Health App.

Unlike dedicated outdoor runners who might utilize this health app data to analyze their running patterns, I consider this dataset a record of my walking activities. This is because I usually exercise in the gym without my device, resulting in no recorded workout information within this dataset.

This statement underscores the value of this dataset. In New York City, walking stands as a routine daily activity amidst various social engagements like commuting, shopping, socializing with friends, and increasingly, leisurely strolls within the city."

The latter analysis was conducted based on above background. 




### Data preparation

```{r}
data <- read.csv("walking_data.csv")
kable(data[1:15,], caption="Sample raw data")
```

***

**Definition of variables** 

- Date: Activity Date 12-01-2022 to 11-30-2023
- Distance_mi: Walked and run distance per day. Measurement Unit: Mile
- ElevationGain_m: Flights Climbed. A flight of stairs is counted as approximately 10 feet (3 meters) of elevation gain (approximately 16 steps) Measurement Unit: Floor
- Steps: Number of steps taken per day. Measurement Unit: Step


### Q1: How many steps/how far did I walk every day in each month?


```{r}
# Convert the 'Date' column to a Date format
data$Date <- as.Date(data$Date, format = "%m-%d-%Y")

# Extract month and year information
data$Month <- format(data$Date, "%Y-%m")

# Calculate daily average steps and distance per month
monthly_avg <- data %>%
  group_by(Month, Date) %>%
  summarise(Avg_Steps = mean(Steps), Avg_Distance = mean(Distance_mi)) %>%
  group_by(Month) %>%
  summarise(Daily_Avg_Steps = mean(Avg_Steps), Daily_Avg_Distance = mean(Avg_Distance))

# Create an interactive plot with plotly for daily average steps and distance per month
plot <- plot_ly(monthly_avg, x = ~Month) %>%
  add_trace(y = ~Daily_Avg_Steps, name = "Daily Avg Steps", type = 'bar', 
            marker = list(color = 'skyblue', line = list(color = 'black', width = 1))) %>%
  add_trace(y = ~Daily_Avg_Distance, name = "Daily Avg Distance", type = 'scatter', mode = 'lines', yaxis = 'y2') %>%
  layout(title = "Daily Average Steps and Distance per Month",
         xaxis = list(title = "Month"),
         yaxis = list(title = "Daily Average Steps", side = 'left'),
         yaxis2 = list(title = "Daily Average Distance (mi)", side = 'right', overlaying = "y", showgrid = FALSE),
         hoverinfo = 'text',
         text = ~paste("Month: ", Month, "<br>Daily Average Steps: ", Daily_Avg_Steps, "<br>Daily Average Distance: ", Daily_Avg_Distance))
         
# Display the plot
plot

```


***
I was aiming to compare the average walking steps and distance I took in each month. Since "Month" is a categorical variable, Steps and Distance are continuous variables, histogram and line chart were chosen for visualization purpose. I combined histogram for "steps" added with lines displaying "distance" information to make a concise summary of the two varaibles. X-axis is month, and Y-axis are steps and distance. 

The graph illustrates a notable similarity in the patterns between steps and distance throughout the months. This correlation is expected as these variables are strongly correlated - an increase in my daily steps corresponds to an increase in the total walking distance.

From the plot, on average I walked around 8,700 steps and 3.75 miles every day, however, the average numbers vary from one month to another.


### Q2: How many floors did I climb every day?

```{r  include=FALSE}
# Define the categories for elevation gain (split into 5 categories)
data$ElevationCategory <- cut(data$ElevationGain_m, breaks = c(0, 3, 6, 9, 12, max(data$ElevationGain_m)), labels = c("Fl:0-3", "Fl:3-6", "Fl:6-9", "Fl:9-12", "Fl:>12"))

# Calculate the count of data points in each category
category_counts <- table(data$ElevationCategory)

# Labels for the categories
category_labels <- paste(names(category_counts), ": ", category_counts)
```

```{r}
# Create an interactive pie chart with Plotly
plot2<- plot_ly(labels = category_labels, values = category_counts, type = 'pie') %>%
  layout(title = "Elevation Gain Categories")

# Show the colorful interactive histogram
plot2

```


***
Since I was more interested to take a look at the overall of my climbing activity, Pie chart was applied to simply and intuitively display the relative proportions of the climbed data. 

The pie chart illustrates that my daily climbing typically ranged from 0 to 6 floors. It's important to note that this data captures movements while I had my phone, excluding instances when I used the stairs machine at the gym. Moreover, I have elevator access in my residential and office buildings, minimizing stair usage at home or the office. Thus, this climbing activity occurred inadvertently.


### Q3: Do I go out more on weekends than weekdays?
```{r  include=FALSE}
# Convert 'Date' column to Date format if it's not already in Date format
data$Date <- as.Date(data$Date, format = "%m-%d-%Y")


# Create a new column for the week number
data <- data %>%
  mutate(Week = format(Date, "%Y-%U"))

# Define a function to calculate average steps for weekdays and weekends
calculate_avg_steps <- function(group) {
  weekdays_data <- filter(group, !weekdays(Date) %in% c("Saturday", "Sunday"))
  weekends_data <- filter(group, weekdays(Date) %in% c("Saturday", "Sunday"))
  avg_weekday_steps <- mean(weekdays_data$Steps)
  avg_weekend_steps <- mean(weekends_data$Steps)
  return(data.frame(Avg_Weekday_Steps = avg_weekday_steps, Avg_Weekend_Steps = avg_weekend_steps))
}

# Group by 'Week' and calculate averages
result <- data %>%
  group_by(Week) %>%
  do(calculate_avg_steps(.)) %>%
  ungroup() %>%
  mutate(Week = row_number())  # Assign week numbers starting from 1
```
```{r}
# Create a box plot
plot_data <- result[, c("Avg_Weekday_Steps", "Avg_Weekend_Steps")]

# Convert the data to long format for box plot representation
plot_data_long <- tidyr::gather(data.frame(plot_data), key = "Type", value = "Steps")

# Create an interactive box plot using plotly
plot3 <- plot_ly(plot_data_long, x = ~Type, y = ~Steps, color = ~Type, type = "box") %>%
  layout(title = "Average Steps Comparison (Weekdays vs Weekends)",
         xaxis = list(title = "Step Type"),
         yaxis = list(title = "Average Daily Steps"))

# Show the colorful interactive histogram
plot3


```


***
A box plot is a visual tool used in statistics to understand the distribution of a dataset and identify characteristics such as central tendency, dispersion, and skewness. It provides a graphical representation of the five-number summary: minimum, first quartile (Q1), median (second quartile, Q2), third quartile (Q3), and maximum.

The box plot effectively addresses this inquiry. The plot reveals a wider range in my outdoor activities on weekends compared to weekdays, signifying greater variability in weekend events influenced, most probably, by my mood. Weekends often reflect flexibility—some days I may feel "LAZY" - inclined to relax indoors, while others spur excitement for outdoor ventures. Consequently, the majority of my weekend daily step distributions fall within the range of 6150 to 13690, with a median of 9406.

In contrast, my weekday steps exhibit more stability, showcasing a symmetric distribution spanning 6848 to 9343, with a median value of 8080. Although I might adopt a more relaxed approach over the weekend, I appear to maintain relatively higher activity levels compared to weekdays, with a few days showing considerably higher step counts, leading to the upper bound values in the box chart.

Drawing a conclusive statement about my weekend versus weekday outdoor activity based solely on step counts seems challenging. However, it's noticeable that on weekends, when I am outdoors instead of staying home, I tend to engage in longer and more extensive walks compared to weekdays.


### Q4: Which season is my favorite season for outdoor walking? 
```{r  include=FALSE}
# Convert 'Date' column to Date format if it's not already in Date format
data$Date <- as.Date(data$Date, format = "%m-%d-%Y")

# Define a function to categorize months into seasons
get_season <- function(month) {
  if (month %in% 10:12) {
    return("Winter")
  } else if (month %in% 1:3) {
    return("Spring")
  } else if (month %in% 4:6) {
    return("Summer")
  } else {
    return("Autumn")
  }
}

# Create a new column 'Season' based on the month
data$Month <- as.numeric(format(data$Date, "%m"))
data$Season <- sapply(data$Month, get_season)

# Calculate average daily steps for each season
season_avg_steps <- data %>%
  group_by(Season) %>%
  summarise(Avg_Daily_Steps = mean(Steps))

# Display the resulting dataset with average daily steps for each season
print(season_avg_steps)
```
```{r}
# Define colors for each season
colors <- c("Spring" = "#FFD700",  # Gold for Spring
            "Summer" = "#90EE90", # Light Green for Summer
            "Autumn" = "#FF6347", # Tomato Red for Autumn
            "Winter" = "#87CEEB") # Sky Blue for Winter

# Merge colors into the dataset
season_avg_steps$Color <- colors[season_avg_steps$Season]

# Create an interactive histogram using plotly with custom colors
plot <- plot_ly(data = season_avg_steps, x = ~Season, y = ~Avg_Daily_Steps, type = "bar", marker = list(color = ~Color)) %>%
  layout(title = "Average Daily Steps per Season",
         xaxis = list(title = "Season", categoryorder = "array", categoryarray = c("Spring", "Summer", "Autumn", "Winter")),
         yaxis = list(title = "Daily Average Steps"))

# Show the colorful interactive histogram
plot


```

***
In analyzing the data, it's evident that autumn records the highest daily average steps, indicating my preference for outdoor activities during this season. Surprisingly, contrary to common trends, my steps during summer are notably lower compared to other times. This discrepancy is attributed to my avoidance of extreme temperatures; consequently, I tend to stay indoors or engage in gym workouts during the hotter summer months.

### Q5:What's the trend for my daily steps? 

```{r}
# Load necessary libraries
library(forecast)

# Assuming your data is in a dataframe named 'data'
data$Date <- as.Date(data$Date, format = "%m-%d-%Y")

# Create a time series object with daily frequency
steps_ts <- ts(data$Steps, frequency = 365)

# Fit an ARIMA model
fit <- auto.arima(steps_ts)

# Forecast the next 30 days
forecast_steps <- forecast(fit, h = 30)

# Plot the forecast
plot(forecast_steps, xlab = "Date", ylab = "Steps", main = "Forecasted Steps using ARIMA")

# Add tags for forecasted points
point_to_tag <- tail(forecast_steps$mean, 1)
text(time(point_to_tag), point_to_tag, labels = round(point_to_tag, 2), pos = 3, offset = 0.5)

# Calculate date labels for x-axis
date_labels <- as.character(seq(tail(data$Date, 1), by = "day", length.out = length(forecast_steps$mean)))

# Set custom x-axis with dates
axis(1, at = 1:length(forecast_steps$mean), labels = date_labels, cex.axis = 0.7)

```

***
Here I did a time series analysis for daily steps by using ARIMA model to forecast the next 30 days of steps data. In my model, I considered several effects to forecast future steps: Trend (AR term), Seasonality (MA term), and Stationarity (Integrated term).

A time series plot was used to showcase the forecasted steps for future dates based on historical data, highlighting the trend and potential variations expected in the steps taken over the next 30 days. 

The time series plot depicting daily data shows significant fluctuations within the dataset. In earlier analyses, I aggregated the step data on a monthly or seasonal basis, creating a smoother pattern. This new view reveals extreme values in several months (September, October, and November). I recalled during those months I went on hiking and city walks, enjoying the good weather as well as appreciating maple leaves.

Based on the historical steps data, in the following month, which is December 2023, I will take on average, 9376 steps per day.