#If install needed, run below
#install.packages("plotly")

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.1     ✔ stringr   1.5.2
## ✔ ggplot2   4.0.0     ✔ tibble    3.3.0
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(readxl)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
#keep rmarkdown and dataset in same folder to run

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

aiv <- read_excel(
  "Waterfowl/hg_aiv_condition_dataset.xlsx",
  col_types = c(
    "text", "text", "text",
    "numeric", "numeric", "numeric",
    "numeric", "numeric", "numeric", "numeric"
  )
)

mod_aiv <- aiv %>%
  mutate(
    sex = ifelse(female == "1", "female", "male"),
    age = ifelse(adult == "1", "adult", "juvenile"))

group_summary <- mod_aiv %>%
  group_by(name, age, sex) %>%
  summarize(
    percent_positive = mean(antibody_status, na.rm = TRUE) * 100,
    .groups = "drop") %>%
  mutate(
    group = paste(age, sex, sep = " - "))

#plot formation and interactive element via plotly

p <- ggplot(data = group_summary,
       aes(x = group,
           y = percent_positive,
           color = name,
           group = name,
  text = paste(
    "Species:", name,
    "<br>Group:", group,
    "<br>Percent:", round(percent_positive, 1)))) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  ylab("Percent antibody positive") +
  xlab("Age and sex") +
  scale_y_continuous(limits = c(0, 100)) +
  theme_bw()

ggplotly(p, tooltip = "text") %>%
  layout(legend = list(itemclick = "toggle",
                       itemdoubleclick = "toggleothers"))
#ggsave("selfstudy.png", width = 10, height = 5)