Overview

Course Project for ANLY 512: Data Visualization

The Quantified Self

  • Data Source: Mobile Phone
  • Data Type: Time spent oh phone data, and Bedtime data

With the rise of technology, more and more devices and appliances have been made smart. The number of cell phones in use continue to increase, and it is being said that people are beginning to spend more and more time online, as there has been a decline in actual human interactions. I too have been guilty of that behavior, doing any and everything online; shopping, chatting, banking, just to mention a few.

The purpose of this analysis is to deep dive and get a better understanding of my online activities. It is important to note, however, that this data is pulled from my personal cell phone, not work cell phone, personal computer or work computer.

My cellphone is the device I use when I want to wind down. I do little to no work on it, and only use it for personal activities.

Definition of Variables:

  • Social: This the amount of time spent on social applications, such as Instagram, WhatsApp and the Message app. 8* Productivity and Finance: This according to the iPhone app is categorized as time spent on apps such as Microsoft Teams, Mail, Slack, Banking apps, Weather, information and reading, and Calendar.
  • Creativity: Time spent on photos and camera, or any applications used for designing
  • Shopping and food: Time spent on shopping apps such as Walmart, Amazon, and any other shopping applications
  • Other: Time spent on any applications that do not fall under the above-mentioned categories For the purpose of the project, I retrieved a 12-week data, from the start of the semester to the end of the semester. I wanted to gain insight into not only how much time I have spent on my phone, but what I spend the time doing.

A project for ANLY512: Data Visualization

This final class project uses a collection of 1 years of data on my daily walking activity data.

The goal of this project is to collect, analyze and visualize the data using the tools and methods covered in class. Additionally, using the data-driven approach, I will create a summary which answers the following questions based on the data collected: 1) Q1: How many steps/how much distance did I walk every day in each month? 2) Q2: How many floors did I climb every day? 3) Q3: Do I go out more on weekends than weekdays? 4) Q4: Which season is my favorite season for outdoor walking? 5) Q5:What’s the trend for my daily steps?

Before I dive in to plot analysis, I would like to make some clarification of the data set based on my personal situation. This data set, records a series of my outdoor activity data, such as my daily steps, walking distance, and elevated heights (detailed data set description can be found in the next page). The data were obtained through my iPhone Health App.

Unlike outside runners who might carry phone during outdoor exercise so that the device correctly recorded their working-out information, I would treat this data set as a history of my walking activities only. The reason is that I generally work in the gym without my device, that is, no record for my work-out information.

By saying this, this data set is still valuable - residing in New York City, walking is a typical daily activity in the middle of a variety of social activities, such as commute, shopping, aning out with friends, and more and more often, city walk.

The latter analysis are performed based on the above situation.

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

Q1: How many steps/how much distance did I walk everyday in each month?


I was aiming to compare the average walking steps and distance in each month. Since Month is a categorical variable, Steps and Distance are continuous variable, in aim to combine both of continuous variables together in the same plot, I used histogram together with line to summarize the data. X-axis is Month, and there are two variables in Y-axis, Steps and Distance.

By plotting two varaibles in the same chart, we can easily find that Steps and Distance move similarly over month, which makes sense as two varaibles have strong correlations - when my walked more, my daily steps increase as well as the total walking distance increase.

From the plot, on average I walked around 8700 steps and 3.75 miles every day, however, the average numbers vary month over month.

Q2: How many floors did I climb every day?


Since I was more interested to see what how many floors I climbed most commonly, Pie chart was applied to simply display the relative proportions of the climbed data.

From the pie chart, we could find that I climbed about 0-6 floors typically within a day. As this elevation movements happend during the time I held the phone, which obviously excluded the case when I climbed the tadder in the gym, in addition, I didn’t need to climb the stairs to office/home thanks to the advance of elevators. I would say this climb activity happened without awareness.

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


Box plot was well designed to answer this question. From the result of the box, the range in my outdoor activities on weekends vary greater than weekdays - weekends event tend to me more flexible and really depend on my mood. Sometimes I felt lazy to go outside, and sometimes I was so excited to take a breathe outdoors. With this reason, the majority of my weekend daily distributions fall into the range from 6150 to 13690 with the median of 9406. In contrast, my weekday steps seemed more stable, showing a symmetric distribution within 6848 and 9343, with median value of 8080.

However, even if I might be laid-back over the weekend, it seems I was still relatively more active than weekdays, and there were a few days I walked a lot - causing the upper bound value pretty high in the box chart.

It seems hard to make a conclusion that I go out more on weekends than weekdays according my steps records. But I can say that, on weekends, if I go out instead of staying at home, I would tend to walk more and longer than weekdays.

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


We see that in Autumn, I have highest daily average steps. Thus it seems in the past year, autumn is my favorite season to go out. Surprisingly, different to other people, in summer my steps are comparatively lower than other time. This is because I don’t like to be exposed to extreme temperature, so during the summer, I tend to stay at home more or work out in the gym.

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


Here I did a time series analysis with my trend in daily steps by using ARIMA model. In my model, I considered the seasonal effect and white noise.

From the time series plot with daily data, we can see a lot of noise within the data. In the previous analysis, I averaged the steps data on a monthly or seasonally level, thus making it seem smoothier. This time, we can find that, there were some extreme high data in September, I recalled that I did hiking and city walk in the autumn, enjoying the red leaves.

Based on my historical steps data, I made some prediction of my future steps, which are 6900 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

#####
**Course Project for ANLY 512: Data Visualization**

**The Quantified Self**

 * Data Source: **Mobile Phone**
 * Data Type: **Time spent oh phone data, and Bedtime data**
 
With the rise of technology, more and more devices and appliances have been made smart. The number of cell phones in use continue to increase, and it is being said that people are beginning to spend more and more time online, as there has been a decline in actual human interactions. I too have been guilty of that behavior, doing any and everything online; shopping, chatting, banking, just to mention a few.

The purpose of this analysis is to deep dive and get a better understanding of my online activities. It is important to note, however, that this data is pulled from my personal cell phone, not work cell phone, personal computer or work computer.

My cellphone is the device I use when I want to wind down. I do little to no work on it, and only use it for personal activities.

**Definition of Variables:**

 * Social: This the amount of time spent on social applications, such as Instagram, WhatsApp and the Message app.
 8* Productivity and Finance: This according to the iPhone app is categorized as time spent on apps such as Microsoft Teams, Mail, Slack, Banking apps, Weather, information and reading, and Calendar.
 * Creativity: Time spent on photos and camera, or any applications used for designing
 * Shopping and food: Time spent on shopping apps such as Walmart, Amazon, and any other shopping applications
 * Other: Time spent on any applications that do not fall under the above-mentioned categories
For the purpose of the project, I retrieved a 12-week data, from the start of the semester to the end of the semester. I wanted to gain insight into not only how much time I have spent on my phone, but what I spend the time doing.


A project for ANLY512: Data Visualization

This final class project uses a collection of 1 years of data on my daily walking activity data. 

The goal of this project is to collect, analyze and visualize the data using the tools and methods covered in class. Additionally, using the data-driven approach, I will create a summary which answers the following questions based on the data collected:
1) Q1: How many steps/how much distance did I walk every day in each month?
2) Q2: How many floors did I climb every day?
3) Q3: Do I go out more on weekends than weekdays?
4) Q4: Which season is my favorite season for outdoor walking? 
5) Q5:What's the trend for my daily steps? 


Before I dive in to plot analysis, I would like to make some clarification of the data set based on my personal situation. This data set, records a series of my outdoor activity data, such as my daily steps, walking distance, and elevated heights (detailed data set description can be found in the next page). The data were obtained through my iPhone Health App. 

Unlike outside runners who might carry phone during outdoor exercise so that the device correctly recorded their working-out information, I would treat this data set as a history of my walking activities only. The reason is that I generally work in the gym without my device, that is, no record for my work-out information. 

By saying this, this data set is still valuable - residing in New York City, walking is a typical daily activity in the middle of a variety of social activities, such as commute, shopping, aning out with friends, and more and more often, city walk.

The latter analysis are performed based on the above situation. 

### Data preparation

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

***

- Definition of variables: 

- Date: Activity Date
- Post Date
- Month
- Description: Detailed Description of purchases
- Amount: The total amount spent	
- Category
- Year: 2017 or 2018

### Q1: How many steps/how much distance did I walk everyday in each month? 


```{r}
# Assuming your dataset is already loaded and named 'data'
# Convert the 'Date' column to a Date format
# Assuming your dataset is already loaded and named 'data'
# 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 in each month. Since Month is a categorical variable, Steps and Distance are continuous variable, in aim to combine both of continuous variables together in the same plot, I used histogram together with line to summarize the data. X-axis is Month, and there are two variables in Y-axis, Steps and Distance. 

By plotting two varaibles in the same chart, we can easily find that Steps and Distance move similarly over month, which makes sense as two varaibles have strong correlations - when my walked more, my daily steps increase as well as the total walking distance increase. 

From the plot, on average I walked around 8700 steps and 3.75 miles every day, however, the average numbers vary month over month.


### 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 see what how many floors I climbed most commonly, Pie chart was applied to simply display the relative proportions of the climbed data. 

From the pie chart, we could find that I climbed about 0-6 floors typically within a day. As this elevation movements happend during the time I held the phone, which obviously excluded the case when I climbed the tadder in the gym, in addition, I didn't need to climb the stairs to office/home thanks to the advance of elevators. I would say this climb activity happened without awareness. 


### 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


```


***
Box plot was well designed to answer this question. From the result of the box, the range in my outdoor activities on weekends vary greater than weekdays - weekends event tend to me more flexible and really depend on my mood. Sometimes I felt lazy to go outside, and sometimes I was so excited to take a breathe outdoors. With this reason, the majority of my weekend daily distributions fall into the range from 6150 to 13690 with the median of 9406. In contrast, my weekday steps seemed more stable, showing a symmetric distribution within 6848 and 9343, with median value of 8080. 

However, even if I might be laid-back over the weekend, it seems I was still relatively more active than weekdays, and there were a few days I walked a lot - causing the upper bound value pretty high in the box chart. 

It seems hard to make a conclusion that I go out more on weekends than weekdays according my steps records. But I can say that, on weekends, if I go out instead of staying at home, I would tend to walk more and longer than 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" = "#FFA500",  # Orange for Spring
            "Summer" = "#00FF00", # Green for Summer
            "Autumn" = "#FF0000", # Red for Autumn
            "Winter" = "#0000FF") # 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"),
         yaxis = list(title = "Daily Average Steps"))

# Show the colorful interactive histogram
plot


```

***
We see that in Autumn, I have highest daily average steps. Thus it seems in the past year, autumn is my favorite season to go out. Surprisingly, different to other people, in summer my steps are comparatively lower than other time. This is because I don't like to be exposed to extreme temperature, so during the summer, I tend to stay at home more or work out in the gym. 

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

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

# 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(forecast_steps, xlab = "Date", ylab = "Steps", main = "Forecasted Steps using ARIMA")
  

```

***
Here I did a time series analysis with my trend in daily steps by using ARIMA model. In my model, I considered the seasonal effect and white noise. 

From the time series plot with daily data, we can see a lot of noise within the data. In the previous analysis, I averaged the steps data on a monthly or seasonally level, thus making it seem smoothier. This time, we can find that, there were some extreme high data in September, I recalled that I did hiking and city walk in the autumn, enjoying the red leaves. 

Based on my historical steps data, I made some prediction of my future steps, which are 6900 steps per day.