Lars Anderson

Published

December 1, 2024

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?

Figure 1. The experimental arena

Figure 2. The tracking software

Loading and Preparing the Data

Links to raw data: - Treatment A Data - Treatment B Data

Code
# Loading Treatments A/B
a <- 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 zone

b <- 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 step
a <- a |> rename(sand_g = sand, silt_g = silt)

b <- b |> rename(trial_number = x1)

# rename columns to match treatment b data
a <- 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
  )

# Pivoting
a <- a |>
  pivot_longer( 
    cols = ends_with("pct"),  # Replace with the actual column names for substrate types
    names_to = "sub",  # New column for substrate type
    values_to = "pct"  # New column for the percentages
  )

b <- b |> 
  pivot_longer( 
    cols = ends_with("pct"),  # Replace with the actual column names for substrate types
    names_to = "sub",  # New column for substrate type
    values_to = "pct")  # New column for the percentages

# Averages

a_avg <- a |> group_by(sub) |>
        summarise(avg = mean(pct),
                  se = sd(pct) / sqrt(n()),      # Standard error
    ci = 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 error
    ci = 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 general

a <- 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 Gravel
    TRUE ~ "none"                         # Default for any unexpected cases
  ))

# Create the bar plot with magick patterns
a_avg |> 
  ggplot(aes(x = sub, y = avg, fill = sub, pattern_type = pattern_type)) +
  geom_bar_pattern(
    stat = "identity",
    pattern = "magick",                    # Use magick patterns
    pattern_scale = 1.9,                   # Scale the patterns
    pattern_fill = "black",                # Fill color for patterns
    pattern_spacing = 0.5,                # Spacing between patterns
    width = 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 patterns
  
  labs(
    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 frame
b_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 frame
b_avg |> 
  ggplot(aes(x = sub, y = avg)) +  # Avoid mapping 'fill' here, do it in geom_bar_pattern
  geom_bar_pattern(
    aes(fill = I(color_column)),  # Directly use colors from the column
    stat = "identity",
    pattern = "magick",                     # Specify magick pattern
    pattern_type = "crosshatch45",          # Use one specific magick pattern for all bars
    pattern_scale = 1.9,                    # Scale the pattern
    pattern_fill = "black",                 # Pattern color
    pattern_spacing = 0.05,                 # Spacing between patterns
    width = 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 substrate
avg_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 side
avg_timeon_long |> 
  ggplot(aes(x = source, y = value, fill = time_type)) +
  # Bar for both time on substrate and time not on substrate
  geom_bar(
    stat = "identity", 
    color = "black",               # Border color of bars
    position = position_dodge(width = 0.6),  # Side-by-side bars
    width = 0.4                    # Bar width
  ) +
  # Add labels for both bars
  geom_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 uppercase
  scale_fill_manual(
    values = c("avg" = "#CD853F", "time_not_on" = "lightblue"),  # Custom colors for bars
    labels = 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 Server
server <- 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 quadrants
    row = c(1, 1, 2, 2),   # y positions for quadrants
    label = 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 dataset
    sliderInput("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 percentage
      geom_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 values
        mid = "yellow", # Color for middle values
        high = "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 treatment
        x = NULL,  # Remove x-axis label
        y = NULL,  # Remove y-axis label
        fill = "% Time"
      ) +
      theme_minimal() +
      theme(
        plot.title = element_text(size = 20, face = "bold", hjust = 0.5),  # Larger title, bold, and centered
        axis.text.x = element_blank(),  # Remove x-axis numbers
        axis.text.y = element_blank(), # Remove y-axis numbers
        panel.grid.major = element_blank(),  # Remove major grid lines
        panel.grid.minor = element_blank()
      )
  })
}

# Run the app
shinyApp(ui = ui, server = server)