This experiment examined the substrate selection of burbot. Burbot are native to the Great Lakes and are of particular ecological importance.
Fish were placed in the experimental arena (Figure 1.) and recorded for 70 minutes following a 10 minute acclimation period.
Video footage was then analyzed to determine the time spent on each substrate using Ethovision software (Figure 2.).
Most fish never selected a substrate, instead swimming laps around the arena until the end of the trial. These fish were omitted from analysis, which is why there are so few trials used in the rest of the project.
Two treatments were performed. Treatment A featured different substrate textures and treatment B featured different substrate colors.
The principle question of the experiment is: What type of substrate do juvenile burbot select?
# Loading Treatments A/Ba <-read_excel("C:\\Users\\larander\\Desktop\\Data 309\\FINAL PROJ\\rawdata\\A burbs.xlsx") |> janitor::clean_names()b <-read_excel("C:\\Users\\larander\\Desktop\\Data 309\\FINAL PROJ\\rawdata\\Statistics-B-Juv Burb Substrate.xlsx") |> janitor::clean_names()# Mutate B to get % time in each zoneb <- b |>mutate(natural_pct = (natural /total) *100,white_pct = (white / total) *100,black_pct = (black / total) *100,dark_pct = (dark / total) *100 )# Make names unique for next stepa <- a |>rename(sand_g = sand, silt_g = silt)b <- b |>rename(trial_number = x1)# rename columns to match treatment b dataa <- a |>rename_with(.fn =~str_replace(., "percent_", ""), # Remove "percent_".cols =starts_with("percent_") # Apply only to columns starting with "percent_" ) |>rename_with(.fn =~paste0(., "_pct"), # Add "_pct" to the end of the column name.cols =c("coarse", "silt", "sand", "fine") # Apply to these specific columns )# Pivotinga <- a |>pivot_longer( cols =ends_with("pct"), # Replace with the actual column names for substrate typesnames_to ="sub", # New column for substrate typevalues_to ="pct"# New column for the percentages )b <- b |>pivot_longer( cols =ends_with("pct"), # Replace with the actual column names for substrate typesnames_to ="sub", # New column for substrate typevalues_to ="pct") # New column for the percentages# Averagesa_avg <- a |>group_by(sub) |>summarise(avg =mean(pct),se =sd(pct) /sqrt(n()), # Standard errorci =qt(0.975, df =n() -1) * (sd(pct) /sqrt(n())) # 95% CI )b_avg <- b |>group_by(sub) |>summarise(avg =mean(pct),se =sd(pct) /sqrt(n()), # Standard errorci =qt(0.975, df =n() -1) * (sd(pct) /sqrt(n())) # 95% CI )# More mutation to create time spent on substrate. Total time/ 4200 sec (70 minutes of observation) to give a % of time spent on substrate in generala <- a |>mutate(timeon = (total/4200))b <- b |>mutate(timeon = (total/4200))timeon_a <- a |>select(trial_number, timeon) |>distinct()timeon_b <- b |>select(trial_number, timeon) |>distinct()avg_timeon_a <- timeon_a |>mutate(avg =mean(timeon),source ="a")avg_timeon_b <- timeon_b |>mutate(avg =mean(timeon),source ="b") avg_timeon <-bind_rows(avg_timeon_a, avg_timeon_b)a_small <- a |>select(trial_number, sub, pct) a_small$row <-rep(c(1,2,1,2), length.out =120)a_small$col <-rep(c(1,1,2,2), length.out =120)a_small$trial_number <-as.numeric(gsub("Trial\\s*", "", a_small$trial_number))b_small <- b |>select(trial_number, sub, pct) b_small$row <-rep(c(1,2,1,2), length.out =24)b_small$col <-rep(c(1,1,2,2), length.out =24)b_small$trial_number <-as.numeric(gsub("Trial\\s*", "", b_small$trial_number))
Percent time spent on each substrate was used rather than total time, because the software would lose track of the fish if it swam too high in the water column. This means the total time of each fish is different depending on how often they took a lap around. The tracking software would never lose track of the fish if the fish was present on the substrate. The data represents how much time a fish spent on a specific substrate compared to how much time it spent on substrate in general.
Data Visualization
Code
a_avg <- a_avg |>mutate(pattern_type =case_when( sub =="sand_pct"~"crosshatch45", # Example magick pattern for Sand sub =="silt_pct"~"crosshatch30", # Example magick pattern for Silt sub =="coarse_pct"~"hexagons", # Example magick pattern for Coarse Gravel sub =="fine_pct"~"circles", # Example magick pattern for Fine GravelTRUE~"none"# Default for any unexpected cases ))# Create the bar plot with magick patternsa_avg |>ggplot(aes(x = sub, y = avg, fill = sub, pattern_type = pattern_type)) +geom_bar_pattern(stat ="identity",pattern ="magick", # Use magick patternspattern_scale =1.9, # Scale the patternspattern_fill ="black", # Fill color for patternspattern_spacing =0.5, # Spacing between patternswidth =0.7,color ="black" ) +geom_errorbar(aes(ymin = avg - ci, ymax = avg + ci), width =0.2, color ="black") +scale_fill_manual(values =rep("#D2B48C", nrow(a_avg))) +scale_x_discrete(labels =c("silt_pct"="Silt","sand_pct"="Sand","coarse_pct"="Coarse Gravel","fine_pct"="Fine Gravel" )) +scale_pattern_type_discrete(choices =c("circles", "crosshatch30", "hexagons", "crosshatch45", "none")) +# Specify valid patternslabs(title ="Time Spent on Different Substrates (Treatment A)",x ="Substrate Type",y ="% Time Spent on Substrate",fill ="Substrate" ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust = .5),legend.position ="none" )
Code
# Add a color column to your data frameb_avg <- b_avg |>mutate(color_column =case_when( sub =="black_pct"~"black", # Light khaki for Silt sub =="dark_pct"~"#8B4513", # Golden yellow for Sand sub =="natural_pct"~"#CD853F", # Saddle brown for Coarse Gravel sub =="white_pct"~"white"# Peru brown for Fine Gravel ))# Plot with manual color assignment via data frameb_avg |>ggplot(aes(x = sub, y = avg)) +# Avoid mapping 'fill' here, do it in geom_bar_patterngeom_bar_pattern(aes(fill =I(color_column)), # Directly use colors from the columnstat ="identity",pattern ="magick", # Specify magick patternpattern_type ="crosshatch45", # Use one specific magick pattern for all barspattern_scale =1.9, # Scale the patternpattern_fill ="black", # Pattern colorpattern_spacing =0.05, # Spacing between patternswidth =0.7,color ="black"# Border color of bars ) +geom_errorbar(aes(ymin = avg - ci, ymax = avg + ci), width =0.2, color ="black") +scale_x_discrete(labels =c("black_pct"="Black","natural_pct"="Natural","dark_pct"="Dark","white_pct"="White" )) +labs(title ="Time Spent on Different Substrates (Treatment B)",x ="Substrate Type",y ="% Time Spent on Substrate" ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust =0.5),legend.position ="none" )
Code
# Add a column for time not on substrateavg_timeon <- avg_timeon |>mutate(time_not_on = (1- avg))# Reshape the data so that each row represents either "time on substrate" or "time not on substrate"avg_timeon_long <- avg_timeon |>pivot_longer(cols =c("avg", "time_not_on"), names_to ="time_type", values_to ="value")# Plot with bars side by sideavg_timeon_long |>ggplot(aes(x = source, y = value, fill = time_type)) +# Bar for both time on substrate and time not on substrategeom_bar(stat ="identity", color ="black", # Border color of barsposition =position_dodge(width =0.6), # Side-by-side barswidth =0.4# Bar width ) +# Add labels for both barsgeom_text(aes(label =round(value, 3)), vjust =-0.5, size =4, position =position_dodge(width =0.6)) +labs(title ="% Trial Time on and Not on Substrate",x ="Treatment",y ="Average % Time",fill ="Position" ) +scale_x_discrete(labels = toupper) +# Convert x-axis labels to uppercasescale_fill_manual(values =c("avg"="#CD853F", "time_not_on"="lightblue"), # Custom colors for barslabels =c("On Substrate", "Not on Substrate") # Legend labels ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust =0.5),legend.position ="right"# Show the legend on the right ) +ylim(0, max(avg_timeon$avg, avg_timeon$time_not_on) *1.1) # Add space above bars for labels
Code
ui <-fluidPage(titlePanel("Heatmap of % Time Spent in Zones"),sidebarLayout(sidebarPanel(selectInput("treatment_selector", "Select Treatment:", choices =c("Treatment A"="a", "Treatment B"="b"),selected ="a"),uiOutput("trial_slider_ui") # Dynamically render trial slider ),mainPanel(plotOutput("heatmap") ) ))
Code
# Shiny Serverserver <-function(input, output, session) {# Dynamically select dataset based on treatment selected_data <-reactive({if (input$treatment_selector =="a") { a_small } else { b_small } })# Quadrant labels data (static, not affected by trial number) quadrant_labels <-data.frame(col =c(1, 2, 1, 2), # x positions for quadrantsrow =c(1, 1, 2, 2), # y positions for quadrantslabel =c("Sand", "Silt", "Coarse Gravel", "Fine Gravel") )# Dynamically update the trial_slider based on the selected treatment output$trial_slider_ui <-renderUI({ trials <-unique(selected_data()$trial_number) # Get unique trials for selected datasetsliderInput("trial_slider", "Select Trial Number:", min =min(trials), max =max(trials), value =min(trials), step =1,ticks =FALSE) })# Filter data based on trial number filtered_data <-reactive({selected_data() |>filter(trial_number == input$trial_slider) })# Render heatmap output$heatmap <-renderPlot({ggplot() +# Heatmap tiles with percentagegeom_raster(data =filtered_data(), aes(x = col, y = row, fill = pct), interpolate =TRUE) +geom_text(data =filtered_data(), aes(x = col, y = row, label =sprintf("%.1f%%", pct)), color ="black", size =6, nudge_y =-0.2) +# Add quadrant labels (static, not affected by trial number)geom_text(data = quadrant_labels,aes(x = col, y = row, label = label),color ="black",size =6,fontface ="bold" ) +scale_fill_gradient2(low ="blue", # Color for low valuesmid ="yellow", # Color for middle valueshigh ="red",midpoint =50,limits =c(0,100)# Color for high values ) +labs(title =paste("Heatmap for Trial", input$trial_slider, "in Treatment", toupper(input$treatment_selector)), # Capitalize treatmentx =NULL, # Remove x-axis labely =NULL, # Remove y-axis labelfill ="% Time" ) +theme_minimal() +theme(plot.title =element_text(size =20, face ="bold", hjust =0.5), # Larger title, bold, and centeredaxis.text.x =element_blank(), # Remove x-axis numbersaxis.text.y =element_blank(), # Remove y-axis numberspanel.grid.major =element_blank(), # Remove major grid linespanel.grid.minor =element_blank() ) })}# Run the appshinyApp(ui = ui, server = server)
Source Code
---title: "Final Project"subtitle: "Lars Anderson"date: "2024-12-01"format: html: theme: cosmo toc: true toc-title: "Final Project" code-tools: true code-overflow: wrap code-fold: trueexecute: warning: falseruntime: shiny---```{r setup, echo = FALSE, results='hide'}options(repos = c(CRAN = "https://cran.rstudio.com/"))if (!requireNamespace("tidyverse", quietly = TRUE)) install.packages("tidyverse")if (!requireNamespace("ipumsr", quietly = TRUE)) install.packages("ipumsr")if (!requireNamespace("dplyr", quietly = TRUE)) install.packages("dplyr")if (!requireNamespace("ggthemes", quietly = TRUE)) install.packages("ggthemes")if (!requireNamespace("readxl", quietly = TRUE)) install.packages("readxl")if (!requireNamespace("stringr", quietly = TRUE)) install.packages("stringr")if (!requireNamespace("shiny", quietly = TRUE)) install.packages("shiny")if (!requireNamespace("magick", quietly = TRUE)) install.packages("magick")if (!requireNamespace("ggpattern", quietly = TRUE)) install.packages("ggpattern")if (!requireNamespace("gridpattrn", quietly = TRUE)) install.packages("gridpattern")library(gridpattern)library(magick)library(ggpattern)library(tidyverse)library(ipumsr)library(dplyr)library(ggthemes)library(readxl)library(stringr)library(shiny)```## Introduction- This experiment examined the substrate selection of burbot. Burbot are native to the Great Lakes and are of particular ecological importance.<!-- -->- Fish were placed in the experimental arena (Figure 1.) and recorded for 70 minutes following a 10 minute acclimation period.<!-- -->- Video footage was then analyzed to determine the time spent on each substrate using Ethovision software (Figure 2.).<!-- -->- Most fish never selected a substrate, instead swimming laps around the arena until the end of the trial. These fish were omitted from analysis, which is why there are so few trials used in the rest of the project.<!-- -->- Two treatments were performed. Treatment A featured different substrate textures and treatment B featured different substrate colors.<!-- -->- The principle question of the experiment is: What type of substrate do juvenile burbot select?### Loading and Preparing the DataLinks to raw data: - [Treatment A Data](https://docs.google.com/spreadsheets/d/1thk2be2RP9hru8ilpP_-bsjs8YS-Jjd8/edit?usp=drive_link&ouid=101677665788647004019&rtpof=true&sd=true) - [Treatment B Data](https://docs.google.com/spreadsheets/d/1UiwTfdyancwTaRT8HN0I-VwLIrrpu_Yx/edit?usp=drive_link&ouid=101677665788647004019&rtpof=true&sd=true)```{r}# Loading Treatments A/Ba <-read_excel("C:\\Users\\larander\\Desktop\\Data 309\\FINAL PROJ\\rawdata\\A burbs.xlsx") |> janitor::clean_names()b <-read_excel("C:\\Users\\larander\\Desktop\\Data 309\\FINAL PROJ\\rawdata\\Statistics-B-Juv Burb Substrate.xlsx") |> janitor::clean_names()# Mutate B to get % time in each zoneb <- b |>mutate(natural_pct = (natural /total) *100,white_pct = (white / total) *100,black_pct = (black / total) *100,dark_pct = (dark / total) *100 )# Make names unique for next stepa <- a |>rename(sand_g = sand, silt_g = silt)b <- b |>rename(trial_number = x1)# rename columns to match treatment b dataa <- a |>rename_with(.fn =~str_replace(., "percent_", ""), # Remove "percent_".cols =starts_with("percent_") # Apply only to columns starting with "percent_" ) |>rename_with(.fn =~paste0(., "_pct"), # Add "_pct" to the end of the column name.cols =c("coarse", "silt", "sand", "fine") # Apply to these specific columns )# Pivotinga <- a |>pivot_longer( cols =ends_with("pct"), # Replace with the actual column names for substrate typesnames_to ="sub", # New column for substrate typevalues_to ="pct"# New column for the percentages )b <- b |>pivot_longer( cols =ends_with("pct"), # Replace with the actual column names for substrate typesnames_to ="sub", # New column for substrate typevalues_to ="pct") # New column for the percentages# Averagesa_avg <- a |>group_by(sub) |>summarise(avg =mean(pct),se =sd(pct) /sqrt(n()), # Standard errorci =qt(0.975, df =n() -1) * (sd(pct) /sqrt(n())) # 95% CI )b_avg <- b |>group_by(sub) |>summarise(avg =mean(pct),se =sd(pct) /sqrt(n()), # Standard errorci =qt(0.975, df =n() -1) * (sd(pct) /sqrt(n())) # 95% CI )# More mutation to create time spent on substrate. Total time/ 4200 sec (70 minutes of observation) to give a % of time spent on substrate in generala <- a |>mutate(timeon = (total/4200))b <- b |>mutate(timeon = (total/4200))timeon_a <- a |>select(trial_number, timeon) |>distinct()timeon_b <- b |>select(trial_number, timeon) |>distinct()avg_timeon_a <- timeon_a |>mutate(avg =mean(timeon),source ="a")avg_timeon_b <- timeon_b |>mutate(avg =mean(timeon),source ="b") avg_timeon <-bind_rows(avg_timeon_a, avg_timeon_b)a_small <- a |>select(trial_number, sub, pct) a_small$row <-rep(c(1,2,1,2), length.out =120)a_small$col <-rep(c(1,1,2,2), length.out =120)a_small$trial_number <-as.numeric(gsub("Trial\\s*", "", a_small$trial_number))b_small <- b |>select(trial_number, sub, pct) b_small$row <-rep(c(1,2,1,2), length.out =24)b_small$col <-rep(c(1,1,2,2), length.out =24)b_small$trial_number <-as.numeric(gsub("Trial\\s*", "", b_small$trial_number))```Percent time spent on each substrate was used rather than total time, because the software would lose track of the fish if it swam too high in the water column. This means the total time of each fish is different depending on how often they took a lap around. The tracking software would never lose track of the fish if the fish was present on the substrate. The data represents how much time a fish spent on a specific substrate compared to how much time it spent on substrate in general.## Data Visualization```{r}a_avg <- a_avg |>mutate(pattern_type =case_when( sub =="sand_pct"~"crosshatch45", # Example magick pattern for Sand sub =="silt_pct"~"crosshatch30", # Example magick pattern for Silt sub =="coarse_pct"~"hexagons", # Example magick pattern for Coarse Gravel sub =="fine_pct"~"circles", # Example magick pattern for Fine GravelTRUE~"none"# Default for any unexpected cases ))# Create the bar plot with magick patternsa_avg |>ggplot(aes(x = sub, y = avg, fill = sub, pattern_type = pattern_type)) +geom_bar_pattern(stat ="identity",pattern ="magick", # Use magick patternspattern_scale =1.9, # Scale the patternspattern_fill ="black", # Fill color for patternspattern_spacing =0.5, # Spacing between patternswidth =0.7,color ="black" ) +geom_errorbar(aes(ymin = avg - ci, ymax = avg + ci), width =0.2, color ="black") +scale_fill_manual(values =rep("#D2B48C", nrow(a_avg))) +scale_x_discrete(labels =c("silt_pct"="Silt","sand_pct"="Sand","coarse_pct"="Coarse Gravel","fine_pct"="Fine Gravel" )) +scale_pattern_type_discrete(choices =c("circles", "crosshatch30", "hexagons", "crosshatch45", "none")) +# Specify valid patternslabs(title ="Time Spent on Different Substrates (Treatment A)",x ="Substrate Type",y ="% Time Spent on Substrate",fill ="Substrate" ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust = .5),legend.position ="none" )``````{r}# Add a color column to your data frameb_avg <- b_avg |>mutate(color_column =case_when( sub =="black_pct"~"black", # Light khaki for Silt sub =="dark_pct"~"#8B4513", # Golden yellow for Sand sub =="natural_pct"~"#CD853F", # Saddle brown for Coarse Gravel sub =="white_pct"~"white"# Peru brown for Fine Gravel ))# Plot with manual color assignment via data frameb_avg |>ggplot(aes(x = sub, y = avg)) +# Avoid mapping 'fill' here, do it in geom_bar_patterngeom_bar_pattern(aes(fill =I(color_column)), # Directly use colors from the columnstat ="identity",pattern ="magick", # Specify magick patternpattern_type ="crosshatch45", # Use one specific magick pattern for all barspattern_scale =1.9, # Scale the patternpattern_fill ="black", # Pattern colorpattern_spacing =0.05, # Spacing between patternswidth =0.7,color ="black"# Border color of bars ) +geom_errorbar(aes(ymin = avg - ci, ymax = avg + ci), width =0.2, color ="black") +scale_x_discrete(labels =c("black_pct"="Black","natural_pct"="Natural","dark_pct"="Dark","white_pct"="White" )) +labs(title ="Time Spent on Different Substrates (Treatment B)",x ="Substrate Type",y ="% Time Spent on Substrate" ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust =0.5),legend.position ="none" )``````{r}# Add a column for time not on substrateavg_timeon <- avg_timeon |>mutate(time_not_on = (1- avg))# Reshape the data so that each row represents either "time on substrate" or "time not on substrate"avg_timeon_long <- avg_timeon |>pivot_longer(cols =c("avg", "time_not_on"), names_to ="time_type", values_to ="value")# Plot with bars side by sideavg_timeon_long |>ggplot(aes(x = source, y = value, fill = time_type)) +# Bar for both time on substrate and time not on substrategeom_bar(stat ="identity", color ="black", # Border color of barsposition =position_dodge(width =0.6), # Side-by-side barswidth =0.4# Bar width ) +# Add labels for both barsgeom_text(aes(label =round(value, 3)), vjust =-0.5, size =4, position =position_dodge(width =0.6)) +labs(title ="% Trial Time on and Not on Substrate",x ="Treatment",y ="Average % Time",fill ="Position" ) +scale_x_discrete(labels = toupper) +# Convert x-axis labels to uppercasescale_fill_manual(values =c("avg"="#CD853F", "time_not_on"="lightblue"), # Custom colors for barslabels =c("On Substrate", "Not on Substrate") # Legend labels ) +theme_minimal(base_size =14) +theme(plot.title =element_text(hjust =0.5, face ="bold", size =16),axis.text.x =element_text(angle =0, hjust =0.5),legend.position ="right"# Show the legend on the right ) +ylim(0, max(avg_timeon$avg, avg_timeon$time_not_on) *1.1) # Add space above bars for labels``````{r}ui <-fluidPage(titlePanel("Heatmap of % Time Spent in Zones"),sidebarLayout(sidebarPanel(selectInput("treatment_selector", "Select Treatment:", choices =c("Treatment A"="a", "Treatment B"="b"),selected ="a"),uiOutput("trial_slider_ui") # Dynamically render trial slider ),mainPanel(plotOutput("heatmap") ) ))``````{r}# Shiny Serverserver <-function(input, output, session) {# Dynamically select dataset based on treatment selected_data <-reactive({if (input$treatment_selector =="a") { a_small } else { b_small } })# Quadrant labels data (static, not affected by trial number) quadrant_labels <-data.frame(col =c(1, 2, 1, 2), # x positions for quadrantsrow =c(1, 1, 2, 2), # y positions for quadrantslabel =c("Sand", "Silt", "Coarse Gravel", "Fine Gravel") )# Dynamically update the trial_slider based on the selected treatment output$trial_slider_ui <-renderUI({ trials <-unique(selected_data()$trial_number) # Get unique trials for selected datasetsliderInput("trial_slider", "Select Trial Number:", min =min(trials), max =max(trials), value =min(trials), step =1,ticks =FALSE) })# Filter data based on trial number filtered_data <-reactive({selected_data() |>filter(trial_number == input$trial_slider) })# Render heatmap output$heatmap <-renderPlot({ggplot() +# Heatmap tiles with percentagegeom_raster(data =filtered_data(), aes(x = col, y = row, fill = pct), interpolate =TRUE) +geom_text(data =filtered_data(), aes(x = col, y = row, label =sprintf("%.1f%%", pct)), color ="black", size =6, nudge_y =-0.2) +# Add quadrant labels (static, not affected by trial number)geom_text(data = quadrant_labels,aes(x = col, y = row, label = label),color ="black",size =6,fontface ="bold" ) +scale_fill_gradient2(low ="blue", # Color for low valuesmid ="yellow", # Color for middle valueshigh ="red",midpoint =50,limits =c(0,100)# Color for high values ) +labs(title =paste("Heatmap for Trial", input$trial_slider, "in Treatment", toupper(input$treatment_selector)), # Capitalize treatmentx =NULL, # Remove x-axis labely =NULL, # Remove y-axis labelfill ="% Time" ) +theme_minimal() +theme(plot.title =element_text(size =20, face ="bold", hjust =0.5), # Larger title, bold, and centeredaxis.text.x =element_blank(), # Remove x-axis numbersaxis.text.y =element_blank(), # Remove y-axis numberspanel.grid.major =element_blank(), # Remove major grid linespanel.grid.minor =element_blank() ) })}# Run the appshinyApp(ui = ui, server = server)```