#plot 1, Multivariate, General data,
general<-read.csv("general.csv")
personal<-read.csv("personal4.csv")
personal_df<-personal
df<-general
p <- ggplot(df, aes(x=factor(Sleep.duration), y=REM.sleep.percentage,
fill=Smoking.status)) +
geom_boxplot() +
scale_fill_manual(values = c("No" = "blue", "Yes" = "red"),
labels = c("Non-Smoker", "Smoker")) +
scale_y_continuous(breaks = seq(floor(min(df$REM.sleep.percentage,
na.rm = TRUE)),ceiling(max(df$REM.sleep.percentage, na.rm = TRUE)), by = 1)) +
# More ticks on the y-axis
labs(title="REM Sleep Percentage by Sleep Duration",
x="Sleep Duration (hours)",
y="REM Sleep Percentage") +
theme_minimal() +
theme(legend.position="top",
plot.title=element_text(size=14, face="bold", hjust = 0.5),
# Ensuring the title is centered
axis.title=element_text(size=12, face="bold"),
legend.title=element_blank(),
axis.text.x=element_text(angle=45, hjust=1))
# Rotating x-axis labels for readability
# Print the plot
print(p)
#plot 2 Multivariate, Personal Data
# Creating a new categorical variable for summer vs non-summer
personal_df$SeasonCategory <- ifelse(personal_df$season == "summer", "Summer", "Non-Summer")
# Plotting
ggplot(personal_df, aes(x = Sleep.duration, y = Sleep.efficiency, color = SeasonCategory)) +
geom_point() + # scatter plot points
geom_smooth(aes(color = SeasonCategory), method = "lm", se = FALSE) + # ensures separate regression lines for each category
labs(title = "Comparison of Sleep Efficiency and Duration by Season",
x = "Sleep Duration",
y = "Sleep Efficiency") +
theme_minimal() +
scale_color_manual(values = c("Summer" = "blue", "Non-Summer" = "red")) # defines colors for the categories
## `geom_smooth()` using formula = 'y ~ x'
#plot3 Univariate? I think multivariate? General data
# Renaming the dataframe columns appropriately
names(general)[names(general) == "Sleep.duration"] <- "Sleep_duration"
names(general)[names(general) == "REM.sleep.percentage"] <- "REM_sleep_percentage"
names(general)[names(general) == "Alcohol.consumption"] <- "Alcohol_consumption"
# Subset of data where alcohol consumption is not zero
alcohol_consumed <- subset(general, Alcohol_consumption != 0)
# Subset of data where alcohol consumption is zero
no_alcohol_consumed <- subset(general, Alcohol_consumption == 0)
# Define the breaks for the x-axis
x_breaks <- seq(floor(min(general$Sleep_duration)), ceiling(max(general$Sleep_duration)), by = 0.5)
# Plot for observations where alcohol was consumed
p1 <- ggplot(alcohol_consumed, aes(x = Sleep_duration, y = ..density..)) +
geom_histogram(bins = 25, fill = 'blue', alpha = 0.7) +
scale_x_continuous(breaks = x_breaks) +
labs(title= "Alcohol Consumed", x = "Sleep Duration", y = "Density") +
theme_minimal()
# Plot for observations where no alcohol was consumed
p2 <- ggplot(no_alcohol_consumed, aes(x = Sleep_duration, y = ..density..)) +
geom_histogram(bins = 25, fill = 'red', alpha = 0.7) +
scale_x_continuous(breaks = x_breaks) +
labs(title="No Alcohol Consumed", x = "Sleep Duration", y = "Density") +
theme_minimal()
# Combine the plots with a common title and subtitle
combined_plot <- (p1 | p2) +
plot_layout(guides = 'collect') +
plot_annotation(
title = "Density Histograms of Sleep Duration",
theme = theme(plot.title = element_text(hjust = 0.5))
)
# Printing the combined plot
print(combined_plot)
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
#graph 4 Both datasets, multivariate, counting as general
# Plot pie chart for the general dataframe
general_averages <- general %>%
summarise(
REM = mean(Rem.sleep.percentage, na.rm = TRUE),
Deep = mean(Deep.sleep.percentage, na.rm = TRUE),
Light = mean(Light.sleep.percentage, na.rm = TRUE)
) %>%
gather(key = "SleepType", value = "Percentage")
# Calculate average percentages for the personal dataframe
personal_averages <- personal %>%
summarise(
REM = mean(Rem.sleep.percentage, na.rm = TRUE),
Deep = mean(Deep.sleep.percentage, na.rm = TRUE),
Light = mean(Light.sleep.percentage, na.rm = TRUE)
) %>%
gather(key = "SleepType", value = "Percentage")
# Function to format labels with percentages and sleep stage
label_format <- function(type, percentage) {
sprintf("%s\n%.1f%%", type, percentage)
}
pie_general <- ggplot(general_averages, aes(x = "", y = Percentage, fill = SleepType)) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
geom_text(aes(label = label_format(SleepType, Percentage)), position = position_stack(vjust = 0.5), colour="white") +
theme_void() +
labs(title = "General Population Sleep Breakdown") + # Add title here
theme(legend.position = "none", plot.title = element_text(hjust = 0.5))
# Plot pie chart for the personal dataframe
pie_personal <- ggplot(personal_averages, aes(x = "", y = Percentage, fill = SleepType)) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
geom_text(aes(label = label_format(SleepType, Percentage)), position = position_stack(vjust = 0.5), colour="white") +
theme_void() +
labs(title = "My Personal Sleep Breakdown") + # Add title here
theme(legend.position = "none", plot.title = element_text(hjust = 0.5))
# Combine the two pie charts with a common subtitle and caption
pie_combined <- pie_general + pie_personal + plot_layout(ncol = 2) +
plot_annotation(
theme = theme(plot.title = element_text(hjust = 0.5))
)
# Print the combined plot
print(pie_combined)
#graph 5 done
library(ggplot2)
library(dplyr)
library(patchwork)
# Assuming the 'personal' dataframe is already loaded and has the columns 'Sleep.duration', 'REM.sleep.percentage', and 'season'
# Define common axis limits and breaks
x_limits <- c(7, 10) # Assuming sleep duration ranges from 7 to 10 hours
y_limits <- c(15, 35) # Assuming REM sleep percentage ranges from 15 to 35%
x_breaks <- seq(7, 10, by = 0.5) # Breaks at every half hour
# Filter the data for each season and create individual plots with consistent axis limits and breaks
plot_spring <- ggplot(personal %>% filter(season == "spring"), aes(x = Sleep.duration, y = Rem.sleep.percentage)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "springgreen") +
labs(title = "Spring") +
scale_x_continuous(limits = x_limits, breaks = x_breaks) +
scale_y_continuous(limits = y_limits) +
theme_minimal()
plot_summer <- ggplot(personal %>% filter(season == "summer"), aes(x = Sleep.duration, y = Rem.sleep.percentage)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "tomato") +
labs(title = "Summer") +
scale_x_continuous(limits = x_limits, breaks = x_breaks) +
scale_y_continuous(limits = y_limits) +
theme_minimal()
plot_autumn <- ggplot(personal %>% filter(season == "autumn"), aes(x = Sleep.duration, y = Rem.sleep.percentage)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "goldenrod") +
labs(title = "Autumn") +
scale_x_continuous(limits = x_limits, breaks = x_breaks) +
scale_y_continuous(limits = y_limits) +
theme_minimal()
plot_winter <- ggplot(personal %>% filter(season == "winter"), aes(x = Sleep.duration, y = Rem.sleep.percentage)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
labs(title = "Winter") +
scale_x_continuous(limits = x_limits, breaks = x_breaks) +
scale_y_continuous(limits = y_limits) +
theme_minimal()
# Combine the plots into a patchwork with consistent layout
seasonal_patchwork <- plot_spring | plot_summer | plot_autumn | plot_winter
seasonal_patchwork <- seasonal_patchwork + plot_layout(ncol = 2, nrow=2)
# Print the combined plot
seasonal_patchwork
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 10 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 10 rows containing missing values (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 4 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 4 rows containing missing values (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 16 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 16 rows containing missing values (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 12 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 12 rows containing missing values (`geom_point()`).
#graph 6 plotly
personal_df<-read.csv("personal4.csv")
#creating a new column that is just the month each observation is in.
personal_df$month <- month(personal_df$Date)
newplot <- personal_df %>%
plot_ly(x = ~ScreenTime, y = ~Sleep.duration, text = ~season, hoverinfo = 'text+x+y') %>%
add_markers(frame=~month) %>%
layout(title = 'Screen Time vs Sleep Duration for Each Month',
xaxis = list(title = 'Screen Time (hours)'),
yaxis = list(title = 'Sleep Duration (hours)'))
newplot
#graph 7, Shiny app :(
library(shiny)
## Warning: package 'shiny' was built under R version 4.3.2
library(ggplot2)
# Load your dataframe
# personal_df <- read.csv("path_to_your/personal4.csv")
# Define UI
ui <- fluidPage(
titlePanel("Data Exploration Tool"),
sidebarLayout(
sidebarPanel(
selectInput("variable", "Variable:",
choices = colnames(personal_df)),
numericInput("bins", "Number of bins for histogram (if applicable):",
min = 1, max = 50, value = 10)
),
mainPanel(
verbatimTextOutput("summary"),
plotOutput("hist")
)
)
)
# Define server logic
server <- function(input, output) {
# Generate summary
output$summary <- renderPrint({
summary(personal_df[[input$variable]])
})
# Generate histogram
output$hist <- renderPlot({
# Only attempt to plot if the input is a numeric variable
if(is.numeric(personal_df[[input$variable]])) {
ggplot(personal_df, aes_string(x = input$variable)) +
geom_histogram(bins = input$bins) +
theme_minimal() +
xlab(input$variable) +
ggtitle(paste("Histogram of", input$variable))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
#graph 8, general, univariate
library(ggplot2)
# Read the dataset
general <- read.csv("general.csv")
# Assuming 'Caffeine' is the column indicating caffeine consumption
# and 'SleepEfficiency' is the column for sleep efficiency
# We first need to convert the 'Caffeine' variable to a factor with appropriate labels
general$Caffeine <- factor(general$Caffeine, levels = c(0, 1), labels = c("No Caffeine", "Caffeine"))
# Now we create the bar plot
ggplot(general, aes(x = Caffeine, y = Sleep.efficiency, fill = Caffeine)) +
geom_bar(stat = "summary", fun = "mean") +
labs(title = "Comparison of Sleep Efficiency: Caffeine vs No Caffeine",
x = "Caffeine Consumption",
y = "Average Sleep Efficiency") +
theme_minimal()
library(ggplot2)
# Assuming your data frame is named 'general' and is already loaded
# Create the boxplot with y-axis breaks every 2 units
p <- ggplot(general, aes(x = as.factor(Awakenings), y = Rem.sleep.percentage)) +
geom_boxplot(fill = 'red') + # Set all box plots to red
labs(title = 'Boxplot of REM Sleep Percentage by Number of Awakenings',
x = 'Number of Awakenings',
y = 'REM Sleep Percentage') +
theme_minimal() +
theme(legend.position = "none") + # Remove the legend
scale_y_continuous(breaks = seq(from = floor(min(general$Rem.sleep.percentage)),
to = ceiling(max(general$Rem.sleep.percentage)), by = 2)) # Set y-axis breaks
# Print the plot
print(p)