---
title: "1_genomic_characterisation"
author: "Jonah Rodgus"
date: "2024-09-30"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

*loading library*
====================================================================================================================================
```{r}
#install.packages("readxl")
library(readxl)
#install.packages("tidyverse")
library(tidyverse)
#install.packages("janitor")
library(janitor)
#install.packages("writexl")
library(writexl)
#install.packages("ggsci")
library(ggsci)
#install.packages("patchwork")
library(patchwork)
#install.packages("ComplexUpset")
library(ComplexUpset)
#install.packages("patchwork")
library(patchwork)
#install.packages("scatterpie")
library(scatterpie)
#install.packages("scales")
library(scales)
#install.packages("viridis")
library(viridis)
#install.packages("ggstream")
library(ggstream)
#install.packages("ggalluvial")
library(ggalluvial)
#install.packages("grid")
library(grid)
#install.packages("vctrs")
library(vctrs)
#install.packages("gtable")
library(gtable)
#install.packages("lazyeval")
library(lazyeval)
#install.packages("ggforce")
library(ggforce)
#install.packages("ggtext")
library(ggtext)
#install.packages("plyr")
# BE CAREFUL OF PLYR BECAUSE IT CAN MESS UP %>% PIPING
#library(plyr)
```

*uploading abricate data, mobtyper data, and plasmid kleborate data*
=====================================================================================================================================
# amr genes
# abricate data
```{r}
abricate<-read_tsv("/Users/jonahrodgus/Desktop/declutter/genomic_analyses/colebook/3_char_genomes/all_isolates_abricate.tsv",
                   col_names = TRUE)

# making column names lowercase
colnames(abricate)<-tolower(colnames(abricate))

# converting to data frame
abricate<-as.data.frame(abricate)

abricate_c<-abricate %>%
  # renaming first column
  mutate(isolate_code=as.factor(sample_id) %>%
           fct_reorder(parse_number(sample_id))) %>%
  select(-sample_id) %>%
  relocate(isolate_code,.before = everything()) %>%
  # reordering rows
  arrange(parse_number(as.character(isolate_code)))
```
# mobtyper data
```{r}
mobtyper<-read_tsv(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/colebook/4_char_plasmids/all_mobtyper_results.tsv",
                           col_names = TRUE)

# making column names lowercase
colnames(mobtyper)<-tolower(colnames(mobtyper))

mobtyper<-mobtyper %>%
  # renaming and reordering columns
  separate(sample_id, into=c("isolate_code","plasmid_id"),sep=":") %>%
  # selecting columns of interest
  select(isolate_code,
         plasmid_id,
         size,
         `rep_type(s)`,
         `relaxase_type(s)`,
         predicted_mobility) %>%
  mutate(isolate_code = gsub("_filtered","",isolate_code) %>%
           fct_reorder(parse_number(isolate_code))) %>%
  relocate(isolate_code,.before = everything()) %>%
  # reordering rows
  arrange(parse_number(as.character(isolate_code)))
```
# plasmid abricate data
```{r}
plasmid_abricate<-read_tsv(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/colebook/4_char_plasmids/all_plasmids_abricate.tsv",
                           col_names = TRUE)
#View(plasmid_abricate)
colnames(plasmid_abricate)<-tolower(colnames(plasmid_abricate))

# colebrook
plasmid_abricate<-plasmid_abricate %>%
  select(isolate_code=sample_id,
         plasmid_id,
         sequence,
         start,
         end,
         gene,
         `%coverage`) %>%
  mutate(isolate_code = fct_reorder(isolate_code, parse_number(as.character(isolate_code)))) %>%
  arrange(parse_number(as.character(isolate_code)))
```
# joining all abricate data with mobtyper data
```{r}
# creating all_args data frame
all_args <- 
  # colebrook
  abricate_c %>%
  select(isolate_code:end,
         gene,
         database,
         drug=resistance,
         `%coverage`) %>%
  # verifying genes found across both abricate runs
  left_join(plasmid_abricate,
            by = c("isolate_code",
                   "sequence",
                   "start",
                   "end",
                   "gene",
                   "%coverage")) %>%
  left_join(mobtyper,
            by = c("isolate_code",
                   "plasmid_id"))

# colebrook  
# note 10 instances where left joining by these three field leads to an unexpected many-to-many relationship between `x` and `y`
# local data  

# tidying empty fields
all_args$`rep_type(s)` <- na_if(all_args$`rep_type(s)`, "-")
all_args$`relaxase_type(s)` <- na_if(all_args$`relaxase_type(s)`, "-") 

all_args_c<-all_args
```
# joining amr genes and plasmid data with metadata
```{r}
all_args_c <-
all_args_c %>%
  left_join(colebrook_metadata,
            by="isolate_code") %>%
  select(isolate_code,
         id,
         `collect dt`,
         `pt age`,
         site,
         sequence:predicted_mobility)
```
# hvkp markers
# creating hvkp markers data
```{r}
all_hvkp_markers <-
  char_genomes_c %>%
  select(isolate_code:`collect dt`,
         ST,
         iuc,
         iro,
         rmpA,
         irp2,
         peg344) %>%
  pivot_longer(cols=c(iuc:peg344),
               names_to = "HvKp_marker",
               values_to = "variant") %>%
  filter(!is.na(variant))
```
# peg344 plasmid BLAST data
```{r}
# uploading all 
peg344_plasmid_BLAST <-
  read_tsv(
   # mac mini
  "~/Library/Mobile Documents/com~apple~CloudDocs/Desktop/declutter/genomic_analyses/colebook/4_char_plasmids/all_plasmids_peg344_blast.tsv") %>%
  # separating pipe into left and right
  separate(sseqid, into = c("left", "join"), sep = "\\|") %>%
  # extracting isolate_code and plasmid_id from the 'left' column
  mutate(
    isolate_code = str_extract(left, "^[^_]+"),
    plasmid_id = str_extract(left, "plasmid_([^.]+)\\.fasta") %>% str_remove("plasmid_") %>% str_remove("\\.fasta")
  ) %>%
  # selecting columns of interest
  select(isolate_code,
         plasmid_id,
         `peg344 % identity`=pident) %>%
  mutate(peg344_locus = "TRUE") %>%
  # relocating column
  relocate(peg344_locus, .before = `peg344 % identity`) %>%
  # mostly unimportant
  select(-`peg344 % identity`)
```
# plasmid kleborate data
```{r}
plasmid_kleborate<-read_xlsx(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/colebook/4_char_plasmids/all_plasmids_kleborate.xlsx",
                           col_names = TRUE)
```
# joining plasmid kleborate data with mobtyper data
```{r}
plasmid_kleborate <-
plasmid_kleborate  %>%
  # renaming and reordering columns
  separate(strain, into=c("isolate_code","plasmid_id"),sep="_plasmid_") %>% 
  select(isolate_code,
         plasmid_id,
         iuc=Aerobactin,
         iro=Salmochelin,
         rmpA2,
         irp2) %>%
  # tidying gene names
   mutate(
      iuc = case_when(
        str_detect(iuc, "iuc 1")  ~ "*iuc1*",
        iuc == "iuc 2"           ~ "*iuc2*",
        str_detect(iuc, "iuc 2A") ~ "*iuc2A*",
        TRUE                            ~ iuc
      ),
      iro = case_when(
        str_detect(iro, "iro 1")  ~ "*iro1*",
        str_detect(iro, "iro 2")  ~ "*iro2*",
        iro == "iro unknown"      ~ "*iroOther*",
        TRUE                              ~ iro
      ),
      irp2 = if_else(str_detect(irp2, "\\d"), "*irp2*", irp2)
    ) %>%
  separate(
      col   = rmpA2,
      # splitting into rmpA and rmp by any other name
      into  = c("rmpA", "rmpA%"),
      sep   = "-",
      fill  = "right",
      extra = "merge",
      remove = FALSE
    ) %>%
    mutate(
      # removing last character (if present) and convert to numeric to represent % coverage
      `rmpA%` = str_remove(`rmpA%`, ".$"), 
      `rmpA%` = as.numeric(`rmpA%`)
      ) %>%
  # adding *s
  mutate(rmpA = if_else(str_detect(rmpA, "rmpA"), paste0("*", rmpA, "*"), rmpA)) %>%
  # removing unwatned columns
  select(-c(rmpA2,`rmpA%`)) %>%
  # removing allele version from rmpA2 column
  mutate(rmpA = str_remove(rmpA, "_.*?(?=\\*)")) %>%
  # removing blank values
  mutate(across(c(iuc:rmpA,irp2), ~ if_else(.x == "" | .x == "-", NA_character_, .x))) %>%
  # creating peg344 column
  left_join(peg344_plasmid_BLAST,
            by = c("isolate_code", "plasmid_id")) %>%
  # marking NAs as false
  mutate(peg344_locus = replace_na(peg344_locus, "FALSE")) %>%
  # creating gene column
  mutate(peg344 = if_else(peg344_locus == "TRUE", "*peg344*", NA)) %>%
  # removing unwanted column
  select(-peg344_locus) %>%
  relocate(peg344, .after = irp2) %>%
  mutate(isolate_code = fct_reorder(isolate_code, parse_number(as.character(isolate_code)))) %>%
  arrange(parse_number(as.character(isolate_code))) %>%
  # marking plasmids that contain 1 or more HvKp markers
  mutate(vir_plasmid = rowSums(across(iuc:peg344, ~ !is.na(.))) > 0) %>%
  relocate(vir_plasmid, .before = "iuc") %>%
  left_join(mobtyper,
            by = c("isolate_code",
                   "plasmid_id")) %>%
  # pivoting longer
  pivot_longer(cols=c(iuc:peg344),
               names_to = "HvKp_marker",
               values_to = "variant") %>%
  relocate(c(HvKp_marker,variant), .before = "size") %>%
  filter(!is.na(variant))

```
# joining hvkp markers data and plasmid data with metadata
```{r}
all_hvkp_markers <-
all_hvkp_markers %>%
  left_join(plasmid_kleborate,
            by = c("isolate_code",
                   "HvKp_marker",
                   "variant"))

all_hvkp_markers_c <- all_hvkp_markers
```
# joining all plasmid gene data (amr genes & hvkp markers)

  > it looks like big plasmids carrying AMR genes are exclusive to smaller plasmids carrying virulence genes 
  
```{r}
all_args_c %>%
  select(isolate_code,
         plasmid_id,
         #`collect dt`:site,
         #plasmid_id,
         #size:predicted_mobility,
         AMR_gene=gene
         ) %>%
  distinct() %>%
  left_join(all_hvkp_markers_c %>%
              select(isolate_code,
                     plasmid_id,
                     
                     vir_plasmid),
            by = c("isolate_code","plasmid_id")) %>%
View()
```

>>>          >>>
>>> PLOTTING >>>
>>>          >>>  

*genomic diversity*
====================================================================================================================================
# description: genomic diversity
```{r}
# number distinct STs
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  count(n_distinct(ST))

# number distinct STs found in 2021
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  group_by(ST) %>%
  # adding a column to mark if ST was found at least once in 2021
  mutate(found_in_2021 = any(format(date, "%Y") == "2021")) %>%
  ungroup() %>%
  group_by(ST,found_in_2021) %>%
  tally() %>%
  filter(found_in_2021 == TRUE)

# number distinct STs exclusive to 2021
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389", "KLEB391", "KLEB098", "KLEB341")) %>%
  # changing date format
  mutate(date = as.Date(date, format = "%d-%m-%Y")) %>%
  group_by(ST) %>%
  # adding a column to check if all occurrences are in 2021
  mutate(exclusive_to_2021 = all(format(date, "%Y") == "2021")) %>%
  ungroup() %>%
  group_by(ST,exclusive_to_2021) %>%
  tally() %>%
  filter(exclusive_to_2021 == TRUE)

# STs constituting three or more isolates
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389", "KLEB391", "KLEB098", "KLEB341")) %>%
  group_by(ST) %>%
  filter(n()>2) %>%
  count(n_distinct(ST)) %>%
  arrange(desc(n))
```
# figure: proportion of top 7 STs and other STs across collection months
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # selecting columns of interest
  select(isolate_code,`collect dt`, ST) %>%
  # recharacterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(top7STs=fct_relevel(top7STs,c("ST15",
                                       "ST37",
                                       "ST307",
                                       "ST133",
                                       "ST23",
                                       "ST13",
                                       "ST147",
                                       "Other STs"))) %>%
  # checking counts
  #group_by(
    #ST
    #top7STs
    #) %>%
  #tally() %>%
  #arrange(desc(n))
  group_by(month=lubridate::floor_date(`collect dt`, "month"),top7STs) %>%
  tally() %>%
  arrange(desc(n)) %>%
View()
  # plotting
  ggplot(aes(x=month, y=n, fill = top7STs)) +
  geom_stream(type = "ridge",alpha = 0.8) +
  #geom_col(position="fill", alpha=0.8) +
  theme_bw() +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  #scale_y_continuous(labels = scales::percent_format(scale = 100)) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        # adding legend border
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ylab("Genome Count") +
  xlab("Date") +
  scale_fill_manual(labels = c("ST15 (n=24)",
                               "ST37 (n=20)",
                               "ST307 (n=19)",
                               "ST133 (n=14)",
                               "ST23 (n=10)",
                               "ST13 (n=11)",
                               "ST147 (n=8)",
                               "Other STs (n=245)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080")) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/4_phylogeny/monthly_st_distribution.jpeg",
       height = 3,
       width = 8)
```
# figure: proportion of top 7 STs and other STs across collection months (version 2)
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # selecting columns of interest
  select(isolate_code,`collect dt`, ST) %>%
  # recharacterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(top7STs=fct_relevel(top7STs,c("Top 7 STs", "Other STs"))) %>%
  # checking counts
  #group_by(
    #ST
    #top7STs
    #) %>%
  #tally() %>%
  #arrange(desc(n))
  group_by(month=lubridate::floor_date(`collect dt`, "month"),top7STs) %>%
  tally() %>%
  arrange(desc(n)) %>%
#View()
  # plotting
  ggplot(aes(x=month, y=n, fill = top7STs)) +
  geom_stream(type = "ridge",alpha = 0.8) +
  #geom_col(position="fill", alpha=0.8) +
  theme_bw() +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  #scale_y_continuous(labels = scales::percent_format(scale = 100)) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        # adding legend border
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ylab("Genome Count") +
  xlab("Date") +
  scale_fill_manual(labels = c("Top 7 STs (n=106)", "Other STs (n=245)"),
                    values = c("#FFA500","#008080")) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       height = 3,
       width = 6)

```
# figure: cumulative proportions of STs
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         ST) %>%
  count(ST, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
#View()
  ggplot(aes(x = rank, y = cum_prop)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "ST Count") +
  scale_y_continuous(labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2)) +
  geom_segment(aes(x = 7,
                   xend = 7,
                   y = 0,
                   yend = 0.293),
               linetype = "dashed",
               size=0.3,
               color = "#FFA500") +
  geom_segment(aes(x = 0,
                   xend = 7,
                   y = 0.293,
                   yend = 0.293),
               linetype = "dashed",
               size=0.3,
               color = "#FFA500") +
  geom_text(aes(x = 9, y = 0.15, label = "Top 7 STs\n(n=106)"),
            inherit.aes = FALSE, angle = -90, size = 3.5, hjust = 0.5, vjust = 0) +
  geom_segment(aes(x = 31,
                   xend = 31,
                   y = 0,
                   yend = 0.584),
               linetype = "dashed",
               size=0.3,
               color = "#008080") +
  geom_segment(aes(x = 0,
                   xend = 31,
                   y = 0.584,
                   yend = 0.584),
               linetype = "dashed",
               size=0.3,
               color = "#008080") +
  geom_text(aes(x = 33, y = 0.29, label = "31 STs with n > 2\n(n=206)"),
            inherit.aes = FALSE, angle = -90, size = 3.5, hjust = 0.5, vjust = 0)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/4_phylogeny/cumulative_proportion_sts.jpeg",
       height = 3,
       width = 6)
```
# description: 1LV STs
```{r}
df <-
char_genomes_c %>%
  filter(str_detect(ST, "1LV")) %>%
  select(isolate_code,
         `collect dt`,
         species=`species...4`,
         `%_composition`,
         ST)

write_xlsx(df, "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/2_analysis_Rmd/current/intermediate_outputs/1LV-STs.xlsx")

char_genomes_c <- char_genomes_c %>%
  mutate(ST = str_replace(ST, "ST13-1LV", "ST13"),
         ST = str_replace(ST, "ST307-1LV", "ST307"))
```

*resistance: genomic*
====================================================================================================================================
# description: genes
```{r}
df<-
all_args_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (inc. Cephalosporins & Pencillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             #str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class!="Other") %>%
  # collapsing genes
  # different logic for blaSHV-chr versus blaSHV-acq
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    #str_detect(gene_cat, "blaCTX-M") ~ "blaCTX-M",
    #str_detect(gene_cat, "blaNDM|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    str_detect(gene, "OXA-181|OXA-48") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9") ~ "blaOXA-Type",
    str_detect(gene, "catA") ~ "catA",
    str_detect(gene, "catB") ~ "catB",
    str_detect(gene, "cmlA") ~ "cmlA",
    str_detect(gene, "dfrA") ~ "dfrA",
    str_detect(gene, "fosA") ~ "fosA",
    str_detect(gene, "fosB") ~ "fosB",
    str_detect(gene, "oqxA") ~ "oqxA",
    str_detect(gene, "oqxB") ~ "oqxB",
    str_detect(gene, "qnrB") ~ "qnrB",
    TRUE ~ gene)) %>%
  # filtering "Other genes"
  filter(gene_cat %!in% c("floR", "cmlA", "catA", "catB", "tet(D)", "tet(A)", "arr-3", "fosA", "dfrA"))

n_distinct(df$gene)

n_distinct(df$drug_class)

df %>%
  group_by(gene) %>%
  tally() %>%
  arrange(desc(n))

```
# colouring by drug class
```{r}
# creating pallete
mypal <- pal_aaas("default", alpha = 0.8)(9)
show_col(mypal)
mypal
```
# figure: genomic resistance profiles
```{r}
# checking for acquired SHV  genes in kleborate data
char_genomes_c %>%
  filter(if_any(c(Bla_acquired:Bla_Carb_acquired), ~ str_detect(.x, "SHV"))) #%>%
#View()

# defining SHV acquired genes
SHV_acquired <- c("blaSHV-56", "blaSHV-187", "blaSHV-71", "blaSHV-31", "blaSHV-5", "blaSHV-26")

# creating upset data
upset <-
all_args_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (inc. Cephalosporins & Pencillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             #str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class!="Other")

# checking drug class levels
levels(as.factor(upset$drug_class))

upset <-
upset %>%
  # collapsing genes
  # different logic for blaSHV-chr versus blaSHV-acq
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    #str_detect(gene_cat, "blaCTX-M") ~ "blaCTX-M",
    #str_detect(gene_cat, "blaNDM|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    str_detect(gene, "OXA-181|OXA-48") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9") ~ "blaOXA-Type",
    str_detect(gene, "catA") ~ "catA",
    str_detect(gene, "catB") ~ "catB",
    str_detect(gene, "cmlA") ~ "cmlA",
    str_detect(gene, "dfrA") ~ "dfrA",
    str_detect(gene, "fosA") ~ "fosA",
    str_detect(gene, "fosB") ~ "fosB",
    str_detect(gene, "oqxA") ~ "oqxA",
    str_detect(gene, "oqxB") ~ "oqxB",
    str_detect(gene, "qnrB") ~ "qnrB",
    TRUE ~ gene))

upset <-
upset %>%
  select(isolate_code,
         gene_cat) %>%
  distinct() %>%
  left_join(char_genomes_c %>%
              # fixing isolate_code column for join
              mutate(isolate_code = str_replace_all(isolate_code, "KLEB0", "KLEB")) %>%
              mutate(isolate_code = str_replace_all(isolate_code, "KLEB0", "KLEB")) %>%
              select(isolate_code,
                     ST,
                     resistance_score,
                     virulence_score,
                     Yersiniabactin:O_type),
            by = "isolate_code") %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  # marking convergence
  mutate(convergent=if_else(virulence_score > 2 &
                              resistance_score > 0,
                            "Convergent",
                            "Non-Convergent")) %>%
  mutate(resistance = if_else(resistance_score == 0,
                              "ESBL-/CPE-",
                              as.character(resistance_score))) %>%
  mutate(resistance = if_else(resistance_score > 1,
                              "CPE+",
                              resistance)) %>%
  mutate(resistance = if_else(resistance_score == 1,
                              "ESBL+/CPE-",
                              resistance)) %>%
  # filtering "Other genes"
  filter(gene_cat %!in% c("floR", "cmlA", "catA", "catB", "tet(D)", "tet(A)", "arr-3", "fosA", "dfrA"))

upset<-
upset %>%
  select(isolate_code,
         top7STs,
         gene_cat) %>%
  pivot_wider(names_from = gene_cat,
              values_from = gene_cat,
              values_fill = FALSE,
              values_fn = ~ TRUE)

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Aminoglycosides
  "aac(6')-Ib-AKT", "aac(3)-IId", "aph(3')-Ia", "aadA2", "aadA1",
  "aac(6')-Ib-cr5", "aac(3)-IIe", "aph(6)-Id", "aph(3'')-Ib",

  # Carbapenems
  "blaOXA-48-Like", "blaOXA-Type",

  # β-Lactams (inc. Cephalosporins & Penicillins)
  "blaSHV-Chromosomal", "blaSHV-Acquired", "blaCTX-M-15", "blaTEM",

  # Fluoroquinolones
  "qnrS1", "aac(6')-Ib-cr5", "oqxA", "oqxB", "qnrB",

  # Macrolides
  #"mph(A)",

  # Sulfonamides
  "sul1", "sul2"

  # Other
  #"floR", "cmlA", "catA", "catB", "tet(D)", "tet(A)",
  #"arr-3", "fosA", "dfrA"
)

# reversing the column order to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:2], rev(sets_ordered))]

# italicising column names
colnames(upset)[3:24] <- paste0("*", colnames(upset)[3:24], "*")

# defining sets
# BE CAREFUL TO LIST CORRECT COLUMNS- the above code filters by n() < X based on plotting
sets <- as.character(colnames(upset)[3:24])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

df <- upset

names(df) <- make.unique(names(df))

df %>%
  select(-c(isolate_code,top7STs)) %>%
  group_by(across(everything())) %>%
  filter(n() > 1) %>%
  ungroup()

# plotting
upset(as.data.frame(upset),
      sets,
      stripes = "white",
      sort_sets=FALSE,
      name = "\n Antimicrobial Resistance Gene Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=2,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              ylim(0,10) +
              scale_y_continuous(labels = scales::number_format(accuracy = 1)) +
              ylab("Genome Count") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "ST"=(
            ggplot(mapping=aes(fill=as.factor(top7STs))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion (%)",
                   fill="ST") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c("#6376a0",
                                           "#a6dace",
                                           "#9da6c3",
                                           "#71c9dd",
                                           "#f5af98",
                                           "#ea705d",
                                           "#33b29f",
                                           "#008080"),
                                # reodering factor levels explicitly in plot
                                limits = c("ST15",
                                           "ST37",
                                           "ST307",
                                           "ST133",
                                           "ST23",
                                           "ST13",
                                           "ST147",
                                           "Other STs")))),
        set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              alpha=0.8),
            ) +
              ylab("\nGenome Count")),
      # colouring by drug class
        queries = list(
          # Aminoglycosides
          upset_query(set = "*aac(6')-Ib-AKT*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(3)-IId*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(3')-Ia*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aadA2*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aadA1*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(6')-Ib-cr5*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(3)-IIe*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(6)-Id*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(3'')-Ib*", fill = "#3B4992CC", color_by = "fill"),
        
          # Carbapenems
          upset_query(set = "*blaOXA-48-Like*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaOXA-Type*", fill = "#EE0000CC", color_by = "fill"),
        
          # β-Lactams (inc. Cephalosporins & Penicillins)
          upset_query(set = "*blaSHV-Chromosomal*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaSHV-Acquired*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaCTX-M-15*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaTEM*", fill = "#008B45CC", color_by = "fill"),
        
          # Fluoroquinolones
          upset_query(set = "*qnrS1*", fill = "#631879CC", color_by = "fill"),
          # upset_query(set = "*aac(6')-Ib-cr5*", fill = "#631879CC", color_by = "fill"),  # Appears in both classes
          upset_query(set = "*oqxA*", fill = "#631879CC", color_by = "fill"),
          upset_query(set = "*oqxB*", fill = "#631879CC", color_by = "fill"),
          upset_query(set = "*qnrB*", fill = "#631879CC", color_by = "fill"),
        
          # Macrolides
          #upset_query(set = "*mph(A)*", fill = "#008280CC", color_by = "fill"),
        
          # Sulfonamides
          upset_query(set = "*sul1*", fill = "#A20056CC", color_by = "fill"),
          upset_query(set = "*sul2*", fill = "#A20056CC", color_by = "fill")
                            # Other
                            #upset_query(set = "floR", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "cmlA", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "catA", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "catB", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "tet(D)", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "tet(A)", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "arr-3", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "fosA", fill = "#808180CC", color_by = "fill"),
                            #upset_query(set = "dfrA", fill = "#808180CC", color_by = "fill")
                            )
              ) +
  theme(axis.text.y = element_markdown())



ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/upset_genotypic_resistance.jpeg",
       width=11.75,
       height=8.5)
```
# description: upset
```{r}
# distinct genomic profiles
upset %>%
  select(-1,
         -2,
         -19) %>%  
  distinct() %>%
  nrow()
```
# figure: heatmap of resistance genes across time
```{r}
heatmap<-
all_args_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # collapsing genes
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    #str_detect(gene_cat, "blaCTX-M") ~ "blaCTX-M",
    #str_detect(gene_cat, "blaNDM|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    str_detect(gene, "OXA-181|OXA-48") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9") ~ "blaOXA-Type",
    str_detect(gene, "catA") ~ "catA",
    str_detect(gene, "catB") ~ "catB",
    str_detect(gene, "cmlA") ~ "cmlA",
    str_detect(gene, "dfrA") ~ "dfrA",
    str_detect(gene, "fosA") ~ "fosA",
    str_detect(gene, "fosB") ~ "fosB",
    str_detect(gene, "oqxA") ~ "oqxA",
    str_detect(gene, "oqxB") ~ "oqxB",
    str_detect(gene, "qnrB") ~ "qnrB",
    TRUE ~ gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             #str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class != "Other")

# reordering genes
desired_order <- c(
  # Aminoglycosides
  "*aadA16*", "*aac(6')-Ib11*", "*aac(6')-Ib-D181Y*", "*aac(6')-Ib-AKT*",
  "*aac(3)-IId*", "*aph(3')-Ia*", "*aadA2*", "*aadA1*", "*aac(3)-IIe*",
  "*aph(6)-Id*", "*aph(3'')-Ib*", "*rmtC*", 
  # Carbapenems
  "*blaNDM-1*", "*blaOXA-48-Like*", "*blaOXA-Type*",
  # beta-lactams (inc. Cephalosporins\n& Penicillins)
  "*blaCMY-6*", "*blaCTX-M-15*", "*blaSHV-Chromosomal*", "*blaSHV-Acquired*", "*blaTEM*",
  # Fluoroquinolones
  "*qnrS1*", "*aac(6')-Ib-cr5*", "*oqxA*", "*oqxB*", "*qnrB*",
  # Macrolides
  #"*mph(A)*", "*erm(B)*",
  # Sulfonamides
  "*sul1*", "*sul2*"
)

heatmap <-
heatmap %>%
  # making amr genes italics
  mutate(gene_cat = paste0("*", gene_cat, "*")) %>%
  # relevelling in reverse order for plot
  mutate(gene_cat = fct_relevel(gene_cat, intersect(rev(desired_order), gene_cat)))

heatmap %>%
  group_by(gene_cat, month = lubridate::floor_date(`collect dt`, "month")) %>%
  mutate(count=n()) %>%
   # filtering by genes that appear more than once in a given month
  filter(count>1) %>%
  ungroup()%>%  mutate(gene_cat=as.factor(gene_cat)) %>%
  # ordering drug classes to match (as closely as possible) those from phenotypic resistance plot
  mutate(drug_class = fct_relevel(drug_class,
    "Aminoglycosides",
    "Carbapenems",
    "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
    "Fluoroquinolones",
    #"Macrolides",
    "Sulfonamides")) %>%
#View()
ggplot(aes(x=month,
             y=gene_cat,
             fill=drug_class
             )) +
  #geom_point(alpha=0.8,
             #size=7) +
  geom_raster(aes(alpha=count)) +
  theme_bw() +
  # date aligned
  scale_x_date(name = "Date",limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_fill_manual(values=c("#3B4992CC","#EE0000CC","#008B45CC","#631879CC","#A20056CC")) +
  guides(alpha=FALSE) +
  theme(axis.title.y = element_blank(),
        axis.title.x = element_text(vjust = -2),
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        #legend.box.spacing.y = unit(0.4, "cm"),
        # ensuring even legend border
        #legend.margin=margin(1,2,2,3, unit = "mm"),
        plot.title = element_text(hjust=0.5),
        # italics
        axis.text.y = element_markdown()) +
  labs(x=F,
       x="Date",
       fill="Drug Class") +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  guides(alpha=F)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/resistance_markers_time.jpeg",
       height=5,
       width=8.27)
```
# figure: ggstream of ARGs drug classes across time
```{r}
heatmap  %>%
  group_by(gene_cat, month = lubridate::floor_date(`collect dt`, "month")) %>%
  # filtering by genes that appear more than once in a given month
  #filter(n()>1) %>%
  ungroup() %>%
  # tallying data
  group_by(month, drug_class) %>%
  tally() %>%
  ungroup() %>%
  #mutate(monthlydrugtotal = n()) %>%
  #ungroup() %>%
  #select(drug_class,month,monthlydrugtotal) %>%
  # ordering drug classes to match (as closely as possible) those from phenotypic resistance plot
  mutate(drug_class = fct_relevel(drug_class,
    "Aminoglycosides",
    "Carbapenems",
    "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
    "Fluoroquinolones",
    #"Macrolides",
    "Sulfonamides")) %>%
#View()
  #distinct() %>%
  # plotting
  ggplot(aes(x=month, y=n, fill = drug_class)) +
  geom_stream(type = "ridge",alpha=0.8) +
  theme_bw() +
  #scale_y_continuous(labels = scales::percent) +
  labs(x="Date",
       y="Genome Count",
       fill="Drug Class") +
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_fill_manual(values=c("#3B4992CC","#EE0000CC","#008B45CC","#631879CC","#A20056CC")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust=0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  guides(alpha=F)

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       height=3,
       width=8)
```
# figure: ggstream of genomic resistance profiles across time
```{r}
# plotting
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # changing date format
  mutate(`collect dt`=as.Date(`collect dt`,format = "%d-%m-%Y")) %>%
  group_by(resistance_profile, month = lubridate::floor_date(`collect dt`, "month")) %>%
  tally() %>%
  ungroup() %>%
#View()
  # plotting
  ggplot(aes(x=month, y=n, fill = resistance_profile)) +
  geom_stream(alpha=0.8, type = "ridge") +
  theme_bw() +
  #scale_y_continuous(labels = scales::percent) +
  labs(x="Date",
       y="Genome Count",
       fill="Genomic Resistance Profile") +
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_fill_manual(values = c("#008080","#FFA500","#ea705d"),
                    labels=c("ESBL-/CPE- (n=256)", "ESBL+/CPE- (n=84)", "CPE+	(n=11)")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust=0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  guides(alpha=F)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/resistance_profiles_time.jpeg",
       height=3,
       width=8)

```
# figure: genomic resistance profiles underlying phenotypic resistance by drug
```{r}
# plotting
AST_and_char_genomes_data %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # filtering for Resistance only
  filter(susceptibility == "Resistant") %>%
  # filtering by drugs of interest
  filter(drug %in% drugs_of_interest) %>%
  # recoding Pip-Taz to tazocin
  mutate(drug = if_else(drug == "Piperacillin-Tazobactam", "Tazocin", drug)) %>%
  # changing date format
  mutate(`collect dt`=as.Date(`collect dt`,format = "%d-%m-%Y")) %>%
  # calculating resistance %s
  group_by(resistance_profile,drug) %>%
  mutate(num = n()) %>%
  ungroup %>%
  group_by(drug) %>%
  mutate(denom = n()) %>%
  ungroup() %>%
  mutate(prop = num/denom) %>%
  # filtering where denominators too low (therefore, misleading)
  #filter(denom > 5) %>%
  select(drug_class, drug, resistance_profile, num, denom) %>%
  distinct() %>%
View()
  select(resistance_profile,drug,drug_class,prop) %>%
  distinct() %>%
  # capitalising drug names - making exception for ESBL
  mutate(drug = if_else(str_detect(drug,"ESBL"),"ESBL", str_to_title(drug))) %>%
  # plotting data
  ggplot(aes(x=drug,y=prop)) +
  labs(y="Proportion (%)", x="Drug", fill="Genomic Resistance Profile") +
  geom_col(aes(fill=resistance_profile),position = "stack", width = 0.8, alpha=0.8) +
  #geom_point(size=2, aes(colour=resistance_profile), alpha=1) +
  #geom_line(aes(colour = resistance_profile, group = resistance_profile), alpha=0.8) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 45,hjust=1),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        #legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        # legend position
        #legend.position = c(0.625, 0.125),
        # adding legend border
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  scale_y_continuous(labels = scales::percent_format(scale = 100)) +
  scale_x_discrete(limit = drug_order) +
  scale_fill_manual(labels = c("ESBL-/CPE-",
                               "ESBL+/CPE-",
                               "CPE+"),
                    values = c("#008080","#FFA500","#ea705d"))

ggsave(plot=last_plot(),
      #"/Users/jonahrodgus/Desktop/new.jpeg",
      "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/genotype_phenotype_resistance.jpeg",
      width=8,
      height=3)
```
# supplementary figure: genomic resistance profiles underlying phenotypic susceptibility
```{r}
# plotting
AST_and_char_genomes_data %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  filter(drug != "NA" &
           # looking at susceptibility profiles
           susceptibility != "Resistant") %>%
  # filtering by drugs of interest
  filter(drug %in% drugs_of_interest) %>%
#View()
  # recoding Pip-Taz to tazocin
  mutate(drug = if_else(drug == "Piperacillin-Tazobactam", "Tazocin", drug)) %>%
  group_by(drug) %>%
  # filtering where denominators too low (therefore, misleading)
  #filter(n() > 5) %>%
  ungroup() %>%
#View()
  # calculating resistance %s
  group_by(resistance_profile,drug) %>%
  mutate(num = n()) %>%
  ungroup %>%
  group_by(drug) %>%
  mutate(denom = n()) %>%
  ungroup() %>%
  mutate(prop = num/denom) %>%
  # filtering where denominators too low (therefore, misleading)
  #filter(denom > 5) %>%
    select(drug_class, drug, resistance_profile, num, denom) %>%
  distinct() %>%
View()
  select(resistance_profile,drug,drug_class,prop) %>%
  distinct() %>%
  # capitalising drug names - making exception for ESBL
  mutate(drug = if_else(str_detect(drug,"ESBL"),"ESBL", str_to_title(drug))) %>%
  # plotting data
  ggplot(aes(x=drug,y=prop)) +
  labs(y="Proportion (%)", x="Drug", fill="Genomic Resistance Profile") +
  geom_col(aes(fill=resistance_profile),position = "stack", width = 0.8, alpha=0.8) +
  #geom_point(size=2, aes(colour=resistance_profile), alpha=1) +
  #geom_line(aes(colour = resistance_profile, group = resistance_profile), alpha=0.8) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 45,hjust=1),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        #legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        # legend position
        #legend.position = c(0.625, 0.125),
        # adding legend border
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  scale_y_continuous(labels = scales::percent_format(scale = 100)) +
  scale_x_discrete(limit = drug_order) +
  scale_fill_manual(labels = c("ESBL-/CPE-",
                               "ESBL+/CPE-",
                               "CPE+"),
                    values = c("#008080","#FFA500","#ea705d"))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/genotype_phenotype_susceptibility.jpeg",
       width=8,
       height=3)
```

  > which genes were responsible for true ESBL and true CPE?
  > which genes were responsible for false ESBL and false CPE?
  
# table: consequential genes
```{r}
df<-
AST_and_char_genomes_data  %>%
  # filtering for colebrook K. pneumoniae isolates
  filter(isolate_code %in% colebrook_final_isolates$isolate_code) %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # filtering for drugs and genomes of interest
  filter(drug %in% c(
    # cephalosporins
    "Ceftazidime",
    "Ceftriaxone",
    # carbapenems
    "Ertapenem",
    "Meropenem")) %>%
#View()
  # creating "no carbapenemase gene" 
  mutate(Bla_ESBL_acquired = if_else(Bla_ESBL_acquired == "-", "No ESBL Gene", Bla_ESBL_acquired),
         Bla_Carb_acquired = if_else(Bla_Carb_acquired == "-", "No Carb Gene", Bla_Carb_acquired)) %>%
  # changing date format
  group_by(drug,resistance_profile,
           Bla_ESBL_acquired,
           Bla_Carb_acquired,
           susceptibility) %>%
  tally() %>%
  # consequential genes
  # carried ESBL or CPE and were resistant
  #filter(resistance_profile %in% c("ESBL+/CPE-", "CPE+"), susceptibility == "Resistant")
  # did not carry either ESBL or CPE but were resistant
  #filter(resistance_profile == "ESBL-/CPE-", susceptibility == "Resistant")
  # discordance
  # carried ESBL or CPE but were susceptible
  filter(resistance_profile %in% c("ESBL+/CPE-", "CPE+"), susceptibility == "Susceptible")
  

df

write_xlsx(df,
           "/Users/jonahrodgus/Desktop/df.xlsx")
```

*hypervirulence*
====================================================================================================================================
# figure: genomic hypervirulence profiles
```{r}
upset <-
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         `collect dt`,
         ST,
         resistance_profile,
         genomic_hypervirulence,
         genomic_convergence,
         iuc_locus:peg344_locus) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # renaming columns to remove _locus
  rename_with(~ str_remove(., "_locus"), .cols = iuc_locus:peg344_locus)

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Loci
  "irp2", "rmpA", "iro", "iuc", "peg344"
)
sets_ordered

# reversing the column order of the genes to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:7], rev(sets_ordered))]

# italicising column names
colnames(upset)[8:12] <- paste0("*", colnames(upset)[8:12], "*")

# defining sets
sets <- as.character(colnames(upset)[8:12])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

# plotting
upset(as.data.frame(upset),
      sets,
      sort_sets=FALSE,
      stripes="white",
      name = "\n Genomic HvKp Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      # selecting counts > 2
      # undecided whether this filter should be used
      #min_size=2,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              ylim(0,200) +
              ylab("Genome Count") +
              theme(axis.title.y = element_text(vjust = 7),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "ST"=(
            ggplot(mapping=aes(fill=as.factor(top7STs))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion(%)",
                   fill="ST") +
              theme(axis.title.y = element_text(vjust = 7),
                    legend.title = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c("#6376a0",
                                           "#a6dace",
                                           "#9da6c3",
                                           "#71c9dd",
                                           "#f5af98",
                                           "#ea705d",
                                           "#33b29f",
                                           "#008080"),
                                # reodering factor levels explicitly in plot
                                limits = c("ST15",
                                           "ST37",
                                           "ST307",
                                           "ST133",
                                           "ST23",
                                           "ST13",
                                           "ST147",
                                           "Other STs")))),
        #"Genomic Resistance Profile"=(
            #ggplot(mapping=aes(fill=as.factor(resistance_profile))) +
              #geom_bar(stat="count", position="fill",alpha=0.8) +
              #scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              #labs(y="",
                   #fill="Genomic Resistance Profile") +
              #theme(axis.title.y = element_text(vjust = -5),
                    #legend.title = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    #legend.margin=margin(4,4,4,4, unit = "mm"),
                    #legend.box.background=element_rect(colour = "black"),
                    #legend.background = element_rect(fill = "white")) +
              #scale_fill_manual(values = c("#008080","#FFA500","#ea705d")))),
      set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              fill="#008080",
                              alpha=0.8)) +
              ylab("\nGenome Count"))) +
  # italicising vir genes
  theme(axis.text.y = element_markdown())

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/upset_HvKp.jpeg",
       width=10,
       height=8.5)
```
# description: upset data
```{r}
upset %>%
  # all false
  #filter(if_all(8:12, ~ .x == FALSE))
  # irp2 only
  filter(if_all(8:11, ~ .x == FALSE) &
           `*irp2*` == TRUE) 
  # 4 or more
  #mutate(across(8:12, ~ .x == "TRUE")) %>%
  #filter(rowSums(select(., 8:12)) > 3)
```
# figure: heatmap of genomic hypervirulence genes across time
```{r}
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         `collect dt`,
         ST,
         resistance_profile,
         genomic_hypervirulence,
         genomic_convergence,
         iuc_locus:peg344_locus) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # renaming columns to remove _locus
  rename_with(~ str_remove(., "_locus"), .cols = iuc_locus:peg344_locus) %>%
  pivot_longer(cols=c(iuc:peg344),
               names_to = "hvkp_marker",
               values_to = "presence") %>%
  filter(presence != "FALSE") %>%
  group_by(hvkp_marker, month = lubridate::floor_date(`collect dt`, "month")) %>%
  mutate(count=n()) %>%
   # filtering by genes that appear more than once in a given month
  #filter(count>1) %>%
  ungroup() %>%  
  mutate(hvkp_marker=as.factor(hvkp_marker)) %>%
  # making genes italics
  mutate(hvkp_marker = paste0("*", hvkp_marker, "*")) %>%
#View()
ggplot(aes(x=month,
             y=hvkp_marker,
             fill=hvkp_marker
             )) +
  #geom_point(alpha=0.8,
             #size=7) +
  geom_raster(aes(alpha=count)) +
  theme_bw() +
  # date aligned
  scale_x_date(name = "Date",limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_y_discrete(limits = c(
  "*peg344*",
  "*iuc*",
  "*iro*",
  "*rmpA*",
  "*irp2*"
  )) +
  scale_fill_nejm() +
  guides(alpha=FALSE) +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        legend.box.spacing = unit(0.4, "cm"),
        # ensuring even legend border
        #legend.margin=margin(1,2,2,3, unit = "mm"),
        plot.title = element_text(hjust=0.5),
        # italics
        axis.text.y = element_markdown()) +
  labs(y=NULL,
       x="Date") +
  guides(fill=F) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/HvKp_markers_time.jpeg",
       width=5,
       height=1.5)
```
#  description: k-o locus serotype predictions
```{r}
# k loci
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  group_by(K_locus) %>%
  tally() %>%
  arrange(desc(n)) %>%
  mutate(perc = n/sum(n)*100)
# 63 known K loci
# KL2 commonest
# KL102 second commonest

# o loci
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  group_by(O_locus) %>%
  tally() %>%
  arrange(desc(n)) %>%
  mutate(perc = n/sum(n)*100)
```
# figure: k-o locus combinations across genomic resistance and hypervirulence profiles
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # labelling unknown K loci
  mutate(K_locus = if_else(str_detect(K_locus,"unknown"), "Unknown", K_locus)) %>%
  # labelling top 20 K loci
  mutate(K_locus = if_else(K_locus %in% c("KL2",
                                          "KL102",
                                          "KL112",
                                          "KL24",
                                          "KL116",
                                          "KL38",
                                          "KL62",
                                          "KL25",
                                          "KL3",
                                          "KL15",
                                          "KL28",
                                          "KL1",
                                          "KL30",
                                          "KL48",
                                          "KL14",
                                          "KL54",
                                          "KL10",
                                          "KL114",
                                          "KL23",
                                          "KL27",
                                          "Unknown"
                                          ), K_locus, "Other"))  %>%
  # labelling unknown O loci
  mutate(O_locus = if_else(str_detect(O_locus,"unknown"), "Unknown", O_locus)) %>%
  # relevelling factors
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(top7STs=fct_relevel(top7STs,c("ST15",
                                       "ST37",
                                       "ST307",
                                       "ST133",
                                       "ST23",
                                       "ST13",
                                       "ST147",
                                       "Other STs"))) %>%
  # tallying loci
  group_by(top7STs,resistance_profile,genomic_hypervirulence,K_locus,O_locus) %>%
  # filtering by most commmon combinations
  #filter(n()>1) %>%
  tally() %>%
  ungroup() %>%
  # reordering y axis - need to be explicit
  mutate(K_locus = fct_relevel(K_locus,
  "Unknown", "Other", "KL62", "KL54", "KL48", "KL38", "KL30",
  "KL3", "KL28", "KL27", "KL25", "KL24", "KL23", "KL2", "KL15",
  "KL14", "KL116", "KL114", "KL112", "KL102", "KL10", "KL1")) %>%
  # relevelling factor
  ggplot(aes(x=O_locus,
             y=K_locus,
             size=n,
             colour=top7STs)) +
  geom_jitter(
  alpha = 0.5,
  position = position_jitter(width = 0.025)) +
  scale_size(range = c(2, 10)) +
  ylab("K Locus (Capsular Polysaccharide)") +
  xlab("O Locus (Lipopolysaccharide)") +
  theme_bw() +
  guides(size=F,alpha=F) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(1,4,2,3, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        #plot title for pannelled figure
        plot.title = element_text(hjust = 0.5),
        plot.margin = margin(0,0.5,0.5,0.5, "cm")) +
  scale_colour_manual(labels = c("ST15 (n=24)",
                               "ST37 (n=20)",
                               "ST307 (n=18)",
                               "ST133 (n=14)",
                               "ST23 (n=10)",
                               "ST13 (n=9)",
                               "ST147 (n=8)",
                               "Other STs (n=248)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080")) +
  facet_grid(resistance_profile~genomic_hypervirulence)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/11_ko_locus_combinations_across_genomic_profiles.jpeg",
       height=11.75,
       width=8.5)
```
# figure: cumulative proportions of k loci
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         K_locus) %>%
  count(K_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  bind_rows(tibble(O_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0)) %>%
  arrange(rank) %>%
#View()
  ggplot(aes(x = rank, y = cum_prop)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "K Loci Count") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2))
  
ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/cumulative_proportion_K_locus.jpeg",
       width=6,
      height=3)
```
# figure: cumulative proportions of o loci
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         O_locus) %>%
  count(O_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  bind_rows(tibble(O_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0)) %>%
  arrange(rank) %>%
#View()
  ggplot(aes(x = rank, y = cum_prop)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "O Loci Count") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2))
  
ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/cumulative_proportion_O_locus.jpeg",
       width=6,
      height=3)
```
# supplementary figure: k-o locus combinations 
```{r}
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # labelling unknown K loci
  mutate(K_locus = if_else(str_detect(K_locus,"unknown"), "Unknown", K_locus)) %>%
  # labelling top 20 K loci
  mutate(K_locus = if_else(K_locus %in% c("KL2",
                                          "KL102",
                                          "KL112",
                                          "KL24",
                                          "KL116",
                                          "KL38",
                                          "KL62",
                                          "KL25",
                                          "KL3",
                                          "KL15",
                                          "KL28",
                                          "KL1",
                                          "KL30",
                                          "KL48",
                                          "KL14",
                                          "KL54",
                                          "KL10",
                                          "KL114",
                                          "KL23",
                                          "KL27",
                                          "Unknown"
                                          ), K_locus, "Other"))  %>%
  # labelling unknown O loci
  mutate(O_locus = if_else(str_detect(O_locus,"unknown"), "Unknown", O_locus)) %>%
  # relevelling factors
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(top7STs=fct_relevel(top7STs,c("ST15",
                                       "ST37",
                                       "ST307",
                                       "ST133",
                                       "ST23",
                                       "ST13",
                                       "ST147",
                                       "Other STs"))) %>%
  # tallying loci
  group_by(top7STs,K_locus,O_locus) %>%
  # filtering by most commmon combinations
  #filter(n()>1) %>%
  tally() %>%
  ungroup() %>%
  # reordering y axis - need to be explicit
  mutate(K_locus = fct_relevel(K_locus,
  "Unknown", "Other", "KL62", "KL54", "KL48", "KL38", "KL30",
  "KL3", "KL28", "KL27", "KL25", "KL24", "KL23", "KL2", "KL15",
  "KL14", "KL116", "KL114", "KL112", "KL102", "KL10", "KL1")) %>%
  # relevelling factor
  ggplot(aes(x=O_locus,
             y=K_locus,
             size=n,
             colour=top7STs)) +
  geom_jitter(
  alpha = 0.5,
  position = position_jitter(width = 0.025)) +
  scale_size(range = c(2, 20)) +
  ylab("K Locus (Capsular Polysaccharide)") +
  xlab("O Locus (Lipopolysaccharide)") +
  theme_bw() +
  guides(size=F,alpha=F) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        axis.text.x = element_text(angle = 45,
                                   hjust = 1,
                                   #vjust = -1
                                   ),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(1,4,2,3, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        #plot title for pannelled figure
        plot.title = element_text(hjust = 0.5),
        plot.margin = margin(0.5,0.5,0.5,0.5, "cm")
        ) +
  scale_colour_manual(labels = c("ST15 (n=24)",
                               "ST37 (n=20)",
                               "ST307 (n=19)",
                               "ST133 (n=14)",
                               "ST23 (n=10)",
                               "ST13 (n=11)",
                               "ST147 (n=8)",
                               "Other STs (n=248)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080"))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/ko_combinations.jpeg",
       height = 8,
       width = 7)
```
# supplementary figure: monthly distribution of k loci 
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # labelling unknown K loci
  mutate(K_locus = if_else(str_detect(K_locus,"unknown"), "Unknown", K_locus)) %>%
  # labelling top 20 K loci
  mutate(K_locus = if_else(K_locus %in% c("KL2",
                                          "KL102",
                                          "KL112",
                                          "KL24",
                                          "KL116",
                                          "KL38",
                                          "KL62",
                                          "KL25",
                                          "KL3",
                                          "KL15",
                                          "KL28",
                                          "KL1",
                                          "KL30",
                                          "KL48",
                                          "KL14",
                                          "KL54",
                                          "KL10",
                                          "KL114",
                                          "KL23",
                                          "KL27",
                                          "Unknown"
                                          ), K_locus, "Other")) %>%
  group_by(month=lubridate::floor_date(`collect dt`, "month"),K_locus) %>%
  tally() %>%
  arrange(desc(n)) %>%
  ggplot(aes(x=month, y=n, fill = K_locus)) +
  geom_stream(type = "ridge",alpha = 0.8) +
  #geom_col(position = "fill",alpha=0.8) +
  #scale_y_continuous(labels = percent_format(accuracy = 1)) + 
  guides(fill=guide_legend(title="K Locus", ncol=3)) +
  theme_bw() +
  ylab("Genome Count") +
  xlab("Date") +
  scale_fill_igv()  +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  guides(alpha=F)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/monthly_distribution_K_locus.jpeg",
       height = 3,
       width = 8)
```
# supplementary figure: monthly distribution of o loci 
```{r}
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # labelling unknown O loci
  mutate(O_locus = if_else(str_detect(O_locus,"unknown"), "Unknown", O_locus)) %>%
  group_by(month=lubridate::floor_date(`collect dt`, "month"),O_locus) %>%
  tally() %>%
  arrange(desc(n)) %>%
#View()
  ggplot(aes(x=month, y=n, fill = O_locus)) +
  geom_stream(type = "ridge",alpha = 0.8) +
  #geom_col(position = "fill",alpha=0.8) +
  #scale_y_continuous(labels = percent_format(accuracy = 1)) + 
  guides(fill=guide_legend(title="O Locus", ncol=2)) +
  theme_bw() +
  ylab("Genome Count") +
  #ylim(0,70) +
  xlab("Date") +
  scale_fill_brewer(palette = "Set3")  +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  guides(alpha=F)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/monthly_distribution_O_locus.jpeg",
       height = 3,
       width = 8)
```

*convergence*
=====================================================================================================================================
# figure: convergence upset
```{r}
upset <-
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         `collect dt`,
         ST,
         resistance_profile,
         genomic_hypervirulence,
         genomic_convergence,
         iuc_locus:peg344_locus) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # renaming columns to remove _locus
  rename_with(~ str_remove(., "_locus"), .cols = iuc_locus:peg344_locus)

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Loci
  "irp2", "rmpA", "iro", "iuc", "peg344"
)
sets_ordered

# reversing the column order of the genes to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:7], rev(sets_ordered))]

# italicising column names
colnames(upset)[8:12] <- paste0("*", colnames(upset)[8:12], "*")

# defining sets
sets <- as.character(colnames(upset)[8:12])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

# plotting
upset(as.data.frame(upset),
      sets,
      sort_sets=FALSE,
      stripes="white",
      name = "\n Genomic HvKp Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      # selecting counts > 2
      # undecided whether this filter should be used
      #min_size=2,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              ylim(0,200) +
              ylab("Genome Count") +
              theme(axis.title.y = element_text(vjust = 7),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "ST"=(
            ggplot(mapping=aes(fill=as.factor(top7STs))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion (%)",
                   fill="ST") +
              theme(axis.title.y = element_text(vjust = 7,hjust=-0.5),
                    legend.title = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c("#6376a0",
                                           "#a6dace",
                                           "#9da6c3",
                                           "#71c9dd",
                                           "#f5af98",
                                           "#ea705d",
                                           "#33b29f",
                                           "#008080"),
                                # reodering factor levels explicitly in plot
                                limits = c("ST15",
                                           "ST37",
                                           "ST307",
                                           "ST133",
                                           "ST23",
                                           "ST13",
                                           "ST147",
                                           "Other STs"))),
        "Genomic Resistance Profile"=(
            ggplot(mapping=aes(fill=as.factor(resistance_profile))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="",
                   fill="Genomic Resistance Profile") +
              theme(axis.title.y = element_text(vjust = -5),
                    #legend.title = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c("#008080","#FFA500","#ea705d")))),
      set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              fill="#008080",
                              alpha=0.8)) +
              ylab("\nGenome Count"))) +
  # italicising vir genes
  theme(axis.text.y = element_markdown())

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/7_convergence/upset_convergence.jpeg",
       width=12,
       height=11)
```
# table: convergence upset
```{r}
upset %>%
  filter(resistance_profile != "ESBL-/CPE-", genomic_hypervirulence == "HvKp+") %>%
#View()
  group_by(top7STs,
           resistance_profile,
           genomic_hypervirulence) %>%
  tally()
```
# defining facet_zoom2 function
## https://stackoverflow.com/questions/52665619/how-to-change-the-position-of-the-zoomed-area-from-facet-zoom
```{r}
facet_zoom2 <- function(x, y, xy, zoom.data, xlim = NULL, ylim = NULL,
                        split = FALSE, horizontal = TRUE, zoom.size = 2,
                        show.area = TRUE, shrink = TRUE) 
{x <- if (missing(x)) if (missing(xy)) NULL else enquo(xy) else enquo(x)
y <- if (missing(y)) if (missing(xy)) NULL else enquo(xy) else enquo(y)
zoom.data <- if (missing(zoom.data)) NULL else enquo(zoom.data)
if (is.null(x) && is.null(y) && is.null(xlim) && is.null(ylim))
{
  cli::cli_abort('Either x- or y-zoom must be given')
}
if (!is.null(xlim)) x <- NULL
if (!is.null(ylim)) y <- NULL
ggproto(NULL, FacetZoom,
        shrink = shrink,
        params = list(
          x = x, y = y, xlim = xlim, ylim = ylim, split = split,
          zoom.data = zoom.data, zoom.size = zoom.size, show.area = show.area,
          horizontal = horizontal
        )
)
}

FacetZoom <- ggproto('FacetZoom', Facet,
                     compute_layout = function(data, params) {
                       layout <- data.frame(
                         name = c('orig', 'x', 'y', 'full', 'orig_true', 'zoom_true'),
                         SCALE_X = c(1L, 2L, 1L, 2L, 1L, 1L),
                         SCALE_Y = c(1L, 1L, 2L, 2L, 1L, 1L)
                       )
                       if (is.null(params$y) && is.null(params$ylim)) {
                         layout <- layout[c(1, 2, 5:6), ]
                       } else if (is.null(params$x) && is.null(params$xlim)) {
                         layout <- layout[c(1, 3, 5:6), ]
                       }
                       layout$PANEL <- seq_len(nrow(layout))
                       layout
                     },
                     map_data = function(data, layout, params) {
                       if (empty(data)) {
                         return(cbind(data, PANEL = integer(0)))
                       }
                       vec_rbind(
                         cbind(data, PANEL = 1L),
                         if (!is.null(params$x)) {
                           index_x <- try_fetch(eval_tidy(params$x, data),
                                                error = function(e) FALSE)
                           if (sum(index_x, na.rm = TRUE) != 0) {
                             cbind(data[index_x, ], PANEL = layout$PANEL[layout$name == 'x'])
                           }
                         },
                         if (!is.null(params$y)) {
                           index_y <- try_fetch(eval_tidy(params$y, data),
                                                error = function(e) FALSE)
                           if (sum(index_y, na.rm = TRUE) != 0) {
                             cbind(data[index_y, ], PANEL = layout$PANEL[layout$name == 'y'])
                           }
                         },
                         if (!is.null(params$zoom.data)) {
                           zoom_data <- try_fetch(eval_tidy(params$zoom.data, data),
                                                  error = function(e) NA)
                           zoom_data <- rep(zoom_data, length.out = nrow(data))
                           zoom_ind <- zoom_data | is.na(zoom_data)
                           orig_ind <- !zoom_data | is.na(zoom_data)
                           vec_rbind(
                             cbind(data[zoom_ind, ], PANEL = if (any(zoom_ind))  layout$PANEL[layout$name == 'zoom_true'] else integer(0)),
                             cbind(data[orig_ind, ], PANEL = if (any(orig_ind)) layout$PANEL[layout$name == 'orig_true'] else integer(0))
                           )
                         }
                       )
                     },
                     train_scales = function(self, x_scales, y_scales, layout, data, params) {
                       # Remove any limits settings on the zoom panels
                       if (length(x_scales) > 1) x_scales[[2]]$limits <- NULL
                       if (length(y_scales) > 1) y_scales[[2]]$limits <- NULL
                       # loop over each layer, training x and y scales in turn
                       for (layer_data in data) {
                         match_id <- match(layer_data$PANEL, layout$PANEL)
                         
                         if (!is.null(x_scales)) {
                           if ('x' %in% layout$name && x_scales[[1]]$is_discrete()) {
                             cli::cli_abort('facet_zoom doesn\'t support zooming in discrete scales')
                           }
                           x_vars <- intersect(x_scales[[1]]$aesthetics,   names(layer_data))
                           SCALE_X <- layout$SCALE_X[match_id]
                           
                           if (!is.null(params$xlim) && length(x_scales) > 1) {
                             x_scales[[2]]$train(x_scales[[2]]$transform(params$xlim))
                             scale_apply(layer_data, x_vars, 'train', SCALE_X, x_scales[-2])
                           } else {
                             scale_apply(layer_data, x_vars, 'train', SCALE_X,    x_scales)
                           }
                         }
                         
                         if (!is.null(y_scales)) {
                           if ('y' %in% layout$name && y_scales[[1]]$is_discrete()) {
                             cli::cli_abort('facet_zoom doesn\'t support zooming in discrete scales')
                           }
                           y_vars <- intersect(y_scales[[1]]$aesthetics, names(layer_data))
                           SCALE_Y <- layout$SCALE_Y[match_id]
                           
                           if (!is.null(params$ylim) && length(y_scales) > 1) {
                             y_scales[[2]]$train(y_scales[[2]]$transform(params$ylim))
                             scale_apply(layer_data, y_vars, 'train', SCALE_Y, y_scales[-2])
                           } else {
                             scale_apply(layer_data, y_vars, 'train', SCALE_Y,  y_scales)
                           }
                         }
                       }
                     },
                     finish_data = function(data, layout, x_scales, y_scales, params)   {
                       plot_panels <- which(!grepl('_true', layout$name))
                       data <- if (is.null(params$zoom.data)) {
                         vec_rbind(!!!lapply(layout$PANEL[plot_panels],   function(panel) {
                           d <- data[data$PANEL == 1, ]
                           d$PANEL <- panel
                           d
                         }))
                       } else {
                         orig_pan <- layout$PANEL[layout$name == 'orig_true']
                         zoom_pan <- layout$PANEL[layout$name == 'zoom_true']
                         orig_data <- data[data$PANEL == orig_pan, ]
                         orig_data$PANEL <- if (nrow(orig_data) != 0) 1L else integer(0)
                         zoom_data <- data[data$PANEL == zoom_pan, ]
                         vec_rbind(orig_data, vec_rbind(!!!lapply(plot_panels[-1], function(panel) {
                           zoom_data$PANEL <- if (nrow(zoom_data) != 0) panel else integer(0)
                           zoom_data
                         })))
                       }
                       data$PANEL <- factor(data$PANEL, layout$PANEL)
                       data
                     },
                     draw_panels = function(self, panels, layout, x_scales, y_scales, ranges, coord,
                                            data, theme, params) {
                       if (inherits(coord, 'CoordFlip')) {
                         cli::cli_abort('facet_zoom doesn\'t work with flipped scales')
                       }
                       if (is.null(params$x) && is.null(params$xlim)) {
                         params$horizontal <- TRUE
                       } else if (is.null(params$y) && is.null(params$ylim)) {
                         params$horizontal <- FALSE
                       }
                       
                       zoom_x <- calc_element('zoom.x', theme)
                       zoom_y <- calc_element('zoom.y', theme)
                       
                       # Construct the panels
                       axes <- render_axes(ranges, ranges, coord, theme, FALSE)
                       panelGrobs <- create_panels(panels, axes$x, axes$y)
                       panelGrobs <- panelGrobs[seq_len(length(panelGrobs) - 2)]
                       
                       if ('full' %in% layout$name && !params$split) {
                         panelGrobs <- panelGrobs[c(1, 4)]
                       }
                       
                       if ('y' %in% layout$name) {
                         if (!inherits(zoom_y, 'element_blank')) {
                           zoom_prop <- rescale(y_scales[[2]]$dimension(expansion(y_scales[[2]])),
                                                from = y_scales[[1]]$dimension(expansion(y_scales[[1]]))
                           )
                           indicator <- polygonGrob(
                             c(0, 0, 1, 1),
                             c(zoom_prop, 1, 0),
                             gp = gpar(col = NA, fill = alpha(zoom_y$fill, 0.5))
                           )
                           lines <- segmentsGrob(
                             y0 = c(1, 1),
                             x0 = c(0, 1),
                             y1 = zoom_prop,
                             x1 = c(1, 1),
                             gp = gpar(
                               col = zoom_y$colour,
                               lty = zoom_y$linetype,
                               lwd = (zoom_y$linewidth %||% zoom_y$size) * .pt,
                               lineend = 'round'
                             )
                           )
                           indicator_h <- grobTree(indicator, lines)
                         } else {
                           indicator_h <- zeroGrob()
                         }
                       }
                       if ('x' %in% layout$name) {
                         if (!inherits(zoom_x, 'element_blank')) {
                           zoom_prop <- rescale(x_scales[[2]]$dimension(expansion(x_scales[[2]])),
                                                from = x_scales[[1]]$dimension(expansion(x_scales[[1]]))
                           )
                           indicator <- polygonGrob(
                             c(zoom_prop, 1, 0),
                             c(1, 1, 0, 0),
                             gp = gpar(col = NA, fill = alpha(zoom_x$fill, 0.5))
                           )
                           lines <- segmentsGrob(
                             x0 = c(0, 1),
                             y0 = c(0, 0),
                             x1 = zoom_prop,
                             y1 = c(1, 1),
                             gp = gpar(
                               col = zoom_x$colour,
                               lty = zoom_x$linetype,
                               lwd = (zoom_x$linewidth %||% zoom_x$size) * .pt,
                               lineend = 'round'
                             )
                           )
                           indicator_v <- grobTree(indicator, lines)
                         } else {
                           indicator_v <- zeroGrob()
                         }
                       }
                       
                       if ('full' %in% layout$name && params$split) {
                         space.x <- theme$panel.spacing.x
                         if (is.null(space.x)) space.x <- theme$panel.spacing
                         space.x <- unit(5 * as.numeric(convertUnit(space.x, 'cm')), 'cm')
                         space.y <- theme$panel.spacing.y
                         if (is.null(space.y)) space.y <- theme$panel.spacing
                         space.y <- unit(5 * as.numeric(convertUnit(space.y, 'cm')), 'cm')
                         final <- gtable_add_cols(panelGrobs[[3]], space.x)
                         final <- cbind(final, panelGrobs[[1]], size = 'first')
                         final_tmp <- gtable_add_cols(panelGrobs[[4]], space.x)
                         final_tmp <- cbind(final_tmp, panelGrobs[[2]], size = 'first')
                         final <- gtable_add_rows(final, space.y)
                         final <- rbind(final, final_tmp, size = 'first')
                         final <- gtable_add_grob(final, list(indicator_h, indicator_h), c(2, 6), 3,
                                                  c(2, 6), 5, z = -Inf, name = 'zoom-indicator')
                         final <- gtable_add_grob(final, list(indicator_v, indicator_v), 3, c(2, 6),
                                                  5, z = -Inf, name = 'zoom-indicator')
                         heights <- unit.c(
                           unit(max_height(list(axes$x[[1]]$top, axes$x[[3]]$top)), 'cm'),
                           unit(1, 'null'),
                           unit(max_height(list(axes$x[[1]]$bottom,    axes$x[[3]]$bottom)), 'cm'),
                           space.y,
                           unit(max_height(list(axes$x[[2]]$top, axes$x[[4]]$top)), 'cm'),
                           unit(params$zoom.size, 'null'),
                           unit(max_height(list(axes$x[[2]]$bottom, axes$x[[4]]$bottom)), 'cm')
                         )
                         widths <- unit.c(
                           ## unit(max_width(list(axes$y[[3]]$left, axes$y[[4]]$left)), 'cm'),
                           ## unit(params$zoom.size, 'null'),
                           ## unit(max_width(list(axes$y[[3]]$right, axes$y[[4]]$right)), 'cm'), space.x,
                           ## unit(max_width(list(axes$y[[1]]$left, axes$y[[2]]$left)), 'cm'),
                           ## unit(1, 'null'),
                           ## unit(max_width(list(axes$y[[1]]$right, axes$y[[2]]$right)), 'cm')
                           
                           unit(max_width(list(axes$y[[1]]$left, axes$y[[2]]$left)), 'cm'),
                           unit(1, 'null'),
                           unit(max_height(list(axes$y[[1]]$right, axes$y[[2]]$right)), 'cm'),
                           space.x,
                           unit(max_width(list(axes$y[[3]]$left, axes$y[[4]]$left)), 'cm'),
                           unit(params$zoom.size, 'null'),
                           unit(max_height(list(axes$y[[3]]$right,     axes$y[[4]]$right)), 'cm')
                         )
                         final$heights <- heights
                         final$widths <- widths
                       } else {
                         if (params$horizontal) {
                           space <- theme$panel.spacing.x
                           if (is.null(space)) space <- theme$panel.spacing
                           space <- unit(5 * as.numeric(convertUnit(space, 'cm')), 'cm')
                           heights <- unit.c(
                             unit(max_height(list(axes$x[[1]]$top, axes$x[[2]]$top)), 'cm'),
                             unit(1, 'null'),
                             unit(max_height(list(axes$x[[1]]$bottom, axes$x[[2]]$bottom)), 'cm')
                           )
                           
                           final <- gtable::gtable_add_cols(panelGrobs[[1]], space) 
                           final <- cbind(final, panelGrobs[[2]], size = "first") 
                           
                           ## final <- gtable_add_cols(panelGrobs[[2]], space)
                           ## final <- cbind(final, panelGrobs[[1]], size = 'first')
                           final$heights <- heights
                           
                           final$widths[panel_cols(final)$l] <- unit(c(1, params$zoom.size), 'null') 
                           ## final$widths[panel_cols(final)$l] <- unit(c(params$zoom.size, 1), 'null')
                           
                           
                           final <- gtable_add_grob(final, indicator_h, 2, 3, 2, 5, z = -Inf,
                                                    name = 'zoom-indicator')
                         } else {
                           space <- theme$panel.spacing.y
                           if (is.null(space)) space <- theme$panel.spacing
                           space <- unit(5 * as.numeric(convertUnit(space, 'cm')),  'cm')
                           widths <- unit.c(
                             unit(max_width(list(axes$y[[1]]$left, axes$y[[2]]$left)), 'cm'),
                             unit(1, 'null'),
                             unit(max_width(list(axes$y[[1]]$right, axes$y[[2]]$right)), 'cm')
                           )
                           final <- gtable_add_rows(panelGrobs[[1]], space)
                           final <- rbind(final, panelGrobs[[2]], size = 'first')
                           final$widths <- widths
                           final$heights[panel_rows(final)$t] <- unit(c(1, params$zoom.size), 'null')
                           final <- gtable_add_grob(final, indicator_v, 3, 2, 5, z = -Inf,
                                                    name = 'zoom-indicator')
                         }
                       }
                       final
                     },
                     draw_back = function(data, layout, x_scales, y_scales, theme, params) {
                       zoom_x <- calc_element('zoom.x', theme)
                       zoom_y <- calc_element('zoom.y', theme)
                       
                       if (!(is.null(params$x) && is.null(params$xlim)) &&
                           params$show.area && !inherits(zoom_x, 'element_blank') && length(x_scales) > 1) {
                         zoom_prop <- rescale(x_scales[[2]]$dimension(expansion(x_scales[[2]])),
                                              from = x_scales[[1]]$dimension(expansion(x_scales[[1]]))
                         )
                         x_back <- grobTree(
                           rectGrob(x = mean(zoom_prop), y = 0.5, width =   diff(zoom_prop),
                                    height = 1,
                                    gp = gpar(col = NA, fill = alpha(zoom_x$fill, 0.5))),
                           segmentsGrob(zoom_prop, c(0, 0), zoom_prop, c(1, 1), gp =    gpar(
                             col = zoom_x$colour,
                             lty = zoom_x$linetype,
                             lwd = (zoom_x$linewidth %||% zoom_x$size) * .pt,
                             lineend = 'round'
                           ))
                         )
                       } else {
                         x_back <- zeroGrob()
                       }
                       if (!(is.null(params$y) && is.null(params$ylim)) &&
                           params$show.area && !inherits(zoom_y, 'element_blank') && length(y_scales) > 1) {
                         zoom_prop <- rescale(y_scales[[2]]$dimension(expansion(y_scales[[2]])),
                                              from = y_scales[[1]]$dimension(expansion(y_scales[[1]]))
                         )
                         y_back <- grobTree(
                           rectGrob(y = mean(zoom_prop), x = 0.5, height = diff(zoom_prop),
                                    width = 1,
                                    gp = gpar(col = NA, fill = alpha(zoom_y$fill, 0.5))),
                           segmentsGrob(y0 = zoom_prop, x0 = c(0, 0), y1 = zoom_prop,    x1 = c(1, 1),
                                        gp = gpar(col = zoom_y$colour,
                                                  lty = zoom_y$linetype,
                                                  lwd = (zoom_y$linewidth %||% zoom_y$size) * .pt,
                                                  lineend = 'round'
                                        )
                           )
                         )
                       } else {
                         y_back <- zeroGrob()
                       }
                       if ('full' %in% layout$name && params$split) {
                         list(grobTree(x_back, y_back), y_back, x_back, zeroGrob(), zeroGrob(),
                              zeroGrob())
                       } else {
                         list(grobTree(x_back, y_back), zeroGrob(), zeroGrob(),     zeroGrob())
                       }
                     }
)
#' @importFrom grid grobHeight grobWidth unit unit.c
#' @importFrom gtable gtable gtable_add_grob
create_panels <- function(panels, x.axis, y.axis) {
  Map(function(panel, x, y, i) {
    heights <- unit.c(grobHeight(x$top), unit(1, 'null'), grobHeight(x$bottom))
    widths <- unit.c(grobWidth(y$left), unit(1, 'null'), grobWidth(y$right))
    table <- gtable(widths, heights)
    table <- gtable_add_grob(table, panel, t = 2, l = 2, z = 2, clip = 'on',
                             name = paste0('panel-', i))
    table <- gtable_add_grob(table, x, t = c(1, 3), l = 2, z = 4, clip = 'off',
                             name = paste0(c('axis-t-', 'axis-b-'), i))
    table <- gtable_add_grob(table, y, t = 2, l = c(1, 3), z = 4, clip = 'off',
                             name = paste0(c('axis-l-', 'axis-r-'), i))
  }, panel = panels, x = x.axis, y = y.axis, i = seq_along(panels))
}

expansion <- function(scale, discrete = c(0, 0.6), continuous = c(0.05, 0)) {
  if (inherits(scale$expand, 'waiver')) {
    if (scale$is_discrete()) {
      discrete
    } else {
      continuous
    }
  } else {
    scale$expand
  }
}

# Helpers       -----------------------------------------------------------------

split_with_index <- function(x, f, n = max(f)) {
  if (n == 1) return(list(x))
  f <- as.integer(f)
  attributes(f) <- list(levels = as.character(seq_len(n)), class = "factor")
  unname(split(x, f))
}

# Function for applying scale method to multiple variables in a given
# data set.  Implement in such a way to minimize copying and hence maximise
# speed
scale_apply <- function(data, vars, method, scale_id, scales) {
  if (length(vars) == 0) return()
  if (nrow(data) == 0) return()
  
  if (any(is.na(scale_id))) {
    cli::cli_abort("{.arg scale_id} must not contain any {.val NA}")
  }
  
  scale_index <- split_with_index(seq_along(scale_id), scale_id,     length(scales))
  
  lapply(vars, function(var) {
    pieces <- lapply(seq_along(scales), function(i) {
      scales[[i]][[method]](data[[var]][scale_index[[i]]])
    })
    # Remove empty vectors to avoid coercion issues with vctrs
    pieces[lengths(pieces) == 0] <- NULL
    o <- order(unlist(scale_index))[seq_len(sum(lengths(pieces)))]
    vec_c(!!!pieces)[o]
  })
}
```
# figure: convergent genomes (replicating plots as in Kochan et al 2023: AMR and hypervirulence convergence)
```{r}
# creating kochan_data
kochan_data <- char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
#View()
  # creating "no carbapenemase gene" 
  mutate(Bla_ESBL_acquired = if_else(Bla_ESBL_acquired == "-", "No ESBL Gene", Bla_ESBL_acquired),
         Bla_Carb_acquired = if_else(Bla_Carb_acquired == "-", "No Carb Gene", Bla_Carb_acquired))

kochan_data <-
kochan_data %>%
  select(isolate_code,
         `collect dt`,
         ST,
         irp2_locus,
         rmpA_locus,
         iro_locus,
         iuc_locus,
         peg344_locus,
         irp2,
         rmpA,
         iro,
         iuc,
         peg344,
         resistance_profile,
         Bla_ESBL_acquired,
         Bla_Carb_acquired,
         genomic_hypervirulence,
         genomic_convergence) %>%
  pivot_longer(cols = c(irp2:peg344),
               names_to = "vir_locus",
               values_to = "vir_gene") %>%
  # tidying gene columns
  mutate(vir_gene=if_else(vir_locus == "irp2" &
                            !is.na(vir_gene), "*irp2*", vir_gene)) %>%
  mutate(vir_gene=if_else(vir_gene == "*rmpA2**", "*rmpA2*", vir_gene)) %>%
  distinct() %>%
  # filtering blank data records
  filter(!is.na(vir_gene)) %>%
  # checking numbers
  #group_by(resistance_profile,vir_gene) %>%
  #tally() %>%
  #arrange(resistance_profile)
#View()
  # reordering factor levels
  mutate(vir_gene = factor(vir_gene,
                           levels=c("*irp2*",
                                    "*rmpA2*",
                                    "*iro1*",
                                    "*iro2*",
                                    "*iroOther*",
                                    "*iuc1*",
                                    "*iuc2*",
                                    "*iuc2A*",
                                    "*peg344*")))


kochan_data %>%
  mutate(ST = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  filter(resistance_profile == "ESBL-/CPE-") %>%
  pivot_wider(names_from = vir_locus,
              values_from = vir_gene) %>%
  group_by(ST, resistance_profile, Bla_ESBL_acquired, Bla_Carb_acquired,irp2, rmpA, iro, iuc, peg344) %>%
  tally()

kochan_data %>%
  ggplot(aes(x=vir_gene,
             fill=resistance_profile)) +
  geom_bar() +
  labs(x=NULL,
       y="Genome Count",
       fill="Genomic Resistance Profile") +
  theme_bw() +
  theme(axis.text.x = element_markdown(angle = 45,hjust=1),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # adding extra white space to bottom to prevent x axis label cutting off
        plot.margin = margin(0.5,0.5,0.5,0.5, unit = "cm"),  # top, right, bottom, left
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black")) +
  #facet_zoom2(ylim = c(0, 50)) +
  scale_fill_manual(labels = c("ESBL-/CPE- (n=256)",
                               "ESBL+/CPE- (n=84)",
                               "CPE+	(n=11)"),
                    values = c("#008080","#FFA500","#ea705d"))

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/10_convergent_genomes.jpeg",
       height=3,
       width=8)
```
# supplementary figure: AMR genes and hypervirulence markers in convergent genomes
```{r}
# plotting
kochan_data %>%
  select(isolate_code,
         `collect dt`,
         ST,
         irp2_locus,
         rmpA_locus,
         iro_locus,
         iuc_locus,
         peg344_locus,
         irp2,
         rmpA,
         iro,
         iuc,
         peg344,
         resistance_profile,
         genomic_hypervirulence,
         genomic_convergence) %>%
  pivot_longer(cols = c(irp2:peg344),
               names_to = "vir_locus",
               values_to = "vir_gene") %>%
  # tidying gene column
  mutate(vir_gene=if_else(vir_locus == "irp2" &
                            !is.na(vir_gene), "*irp2*", vir_gene)) %>%
  mutate(vir_gene=if_else(vir_gene == "*rmpA2**", "*rmpA2*", vir_gene)) %>%
  distinct() %>%
  # reordering factor levels
  mutate(resistance_profile=fct_relevel(resistance_profile,
                                        "ESBL-/CPE-",
                                        "ESBL+/CPE-",
                                        "CPE+")) %>%
  mutate(vir_gene = factor(vir_gene,
                           levels=c("*irp2*",
                                    "*rmpA2*",
                                    "*iro1*",
                                    "*iro2*",
                                    "*iroOther*",
                                    "*iuc1*",
                                    "*iuc2*",
                                    "*iuc2A*",
                                    "*peg344*"))) %>%
  filter(!is.na(vir_gene) &
           resistance_profile %in% c("ESBL+/CPE-","CPE+")) %>%
  # joining with kleborate data
  left_join(char_genomes_c %>%
              select(isolate_code,
                     Bla_ESBL_acquired,
                     Bla_Carb_acquired),
            by = "isolate_code") %>%
  # cleaning genes columns
  # removing special symbols
  mutate(Bla_ESBL_acquired = str_replace(Bla_ESBL_acquired, ";SHV-31.v1*",";blaSHV-Acquired") %>%
           str_remove_all("\\*")) %>%
  mutate(Bla_Carb_acquired = na_if(Bla_Carb_acquired, "-")) %>%
  # separating column lists and pivoting data longer
  separate(Bla_ESBL_acquired, into = c("ESBL_gene_1","ESBL_gene_2"), sep = ";") %>%
  pivot_longer(cols=c(ESBL_gene_1:Bla_Carb_acquired),
               names_to = "kleborate_classification",
               values_to = "amr_gene") %>%
  # filtering by redundant matches
  filter(!is.na(amr_gene)) %>%
  distinct() %>%  
  # reclassifying genes to be consistent with previous plots
  mutate(amr_gene = case_when(
    str_detect(amr_gene, "OXA-181|OXA-48") ~ "blaOXA-48-Like",
    str_detect(amr_gene, "OXA-1|OXA-10|OXA-9") ~ "blaOXA-Type",
    str_detect(amr_gene, "CTX-M-15") ~ "blaCTX-M-15",
    str_detect(amr_gene, "NDM-1") ~ "blaNDM-1",
    TRUE ~ amr_gene)) %>%
  # making arm genes italics
  mutate(amr_gene = paste0("*", amr_gene, "*")) %>%
  # tallying for heatmap
  group_by(amr_gene,vir_gene,resistance_profile) %>%
  tally() %>%
  ungroup() %>%
  # relevelling amr genes
  mutate(amr_gene = fct_relevel(amr_gene,"*blaSHV-Acquired*","*blaCTX-M-15*","*blaOXA-48-Like*","*blaNDM-1*")) %>%
  ggplot(aes(x=vir_gene,
             y=amr_gene,
             fill=resistance_profile
             )) +
  geom_tile(aes(alpha=n)) +
  labs(x="HvKp Marker",
       y="Antimicrobial Resistance Gene",
       fill="Genomic Resistance Profile",
       alpha="Number of Genomes") +
  theme_bw() +
  theme(axis.text.x = element_markdown(angle = 45, hjust=1),
        axis.text.y = element_markdown(),
        axis.title.y = element_text(vjust = 2),
        axis.title.x = element_text(vjust = -2),
        # add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        # adding extra white space to bottom to prevent x axis label cutting off
        plot.margin = margin(0.5,0.5,0.5,0.5, unit = "cm"),  # top, right, bottom, left        
        # tile lines
        #panel.grid.major = element_line(color = "grey80"),
        panel.grid.minor = element_line(color = "grey")) +
  scale_fill_manual(values=c("#FFA500","#ea705d")) +
  scale_alpha(range = c(0.3, 1))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/supplementary/8_suppl_amr_genes_in_convergent_genomes.jpeg",
       height=5,
       width=9)
```

  > which genomes were phenotypically resistant and carried virulence genes?

```{r}
resistant_hvkp_genomes <- 
  char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         `collect dt`,
         ST,
         resistance_profile,
         Bla_ESBL_acquired,
         genomic_hypervirulence,
         genomic_convergence,
         iuc_locus:peg344_locus) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs")) %>%
  relocate(top7STs, .after = ST) %>%
  # renaming columns to remove _locus
  rename_with(~ str_remove(., "_locus"), .cols = iuc_locus:peg344_locus) %>%
  # filtering where all columns = FALSE
  filter(!if_all(iuc:peg344, ~ . == FALSE)) %>%
  # 157 genomes
  # joining with AST data
  left_join(AST_data %>%
              filter(drug %in% drugs_of_interest),
            by = "isolate_code") %>%
  filter(susceptibility == "Resistant") %>%
  # 3 or more HvKp markers?
  mutate(`3HvKp` = rowSums(across(iuc:peg344, ~ as.integer(as.logical(.))), na.rm = TRUE) >= 3) %>%
  filter(`3HvKp` == TRUE)


resistant_hvkp_genomes %>%
  filter(drug != "Ampicillin/Amoxycillin") %>%
  group_by(ST, resistance_profile, drug) %>%
  tally()


resistant_hvkp_genomes %>%
  filter(drug != "Ampicillin/Amoxycillin") %>%
  select(-drug_class) %>%
  pivot_wider(names_from = "drug",
              values_from = "susceptibility") %>%
  select(isolate_code,
         ST,
         resistance_profile,
         ESBL_profile=Bla_ESBL_acquired,
         iuc:peg344,
         `Piperacillin-Tazobactam`:Cotrimoxazole) %>%
  left_join(all_args_c %>%
              mutate(ESBL_profile = if_else(gene == "blaCTX-M-15", "CTX-M-15", "poop")) %>%
              select(isolate_code, ESBL_profile, plasmid_id:predicted_mobility),
            by = c("isolate_code", "ESBL_profile")) %>%
View()

```

*resistance & virulence*
====================================================================================================================================
# description: combinations of resistance scores and virulence scores
```{r}
# tally higher resistance scores (>1) or virulence scores (>3
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  # counting score combinations
  group_by(top7STs, virulence_score > 3 | resistance_score > 1) %>%
  tally()

# high and low scores
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  # counting score combinations
  #group_by(top7STs,resistance_score == 0) %>%
  group_by(top7STs,virulence_score > 4) %>%
  tally()

# breakdown by ST
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  # ST of interest
  # counting score combinations
  group_by(ST == "ST23",virulence_score > 4) %>%
  tally()

```
# figure: genomic resistance profiles and virulence scores by ST
```{r}
# all STs
data <-
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # defining top7STs column
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs (n=106)", "Other STs (n=245)")) %>%
#View()
  # selecting columns of interest
  select(iuc_locus:peg344_locus, resistance_profile, ST, top7STs) %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
#View()
  # counting score combinations
  group_by(virulence_score, resistance_profile) %>%
  mutate(count=n()) %>%
  ungroup() %>%
  # calculating proportions
  group_by(top7STs,virulence_score, resistance_profile) %>%
  mutate(prop = n()/count) %>%
  ungroup() %>%
  select(-ST) %>%
  distinct() %>%
  # pivoting data wider
  pivot_wider(names_from=top7STs,
              values_from=prop) %>%
  select(-count) %>%
  # reordering rows
  arrange(virulence_score) %>%
  # indexing rows
  mutate(label=row_number()) %>%
  # replacing NA values with 0s
  mutate_all(~replace_na(.,0))

data2<-
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))  %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
  # counting score combinations
  group_by(virulence_score,resistance_profile) %>%
  mutate(count=n()) %>%
  select(virulence_score,resistance_profile,count) %>%
  distinct() %>%
  arrange(virulence_score)

data<-data %>%
  # left joining with count data
  left_join(data2,
            by=c("virulence_score","resistance_profile"))

# arbitrary function to define radius
min_x <- 1
max_x <- 151
to_min <- 0.02
to_max <- 0.5

# creating scaling function
scale_values <- function(x, min_x, max_x, to_min, to_max) {
  to_min + (x - min_x) * (to_max - to_min) / (max_x - min_x)
}

# applying scaling function to count values
data$radius <- scale_values(data$count, min_x, max_x, to_min, to_max)

#View()
ggplot() +
  geom_scatterpie(data=data,
                  aes(
                      y=as.numeric(resistance_profile),
                      x=virulence_score,
                      group=label,
                      r=radius),
                  color=NA,
                  cols=colnames(data)[8:9],
                  alpha=0.8) + 
  coord_equal() +
  geom_label(data=data,
             aes(y=(as.numeric(resistance_profile)+radius+0.08),
                 x=virulence_score,
                label=paste0("n=",count)),
                size=3,
             label.padding = unit(0.15, "lines")) +
  theme_bw() +
  ylab("Genomic Resistance Profile") +
  # removing decimals on y axis
  scale_y_continuous(breaks = 0:3) +
  xlab("HvKp Marker Count") +
  scale_fill_manual(labels = c("Other STs (n=245)","Top 7 STs (n=106)"),
                    values = c("#008080","#FFA500"),
                    guide = guide_legend(reverse = TRUE)) +
  theme(axis.title.x  = element_text(vjust = -2),
        #axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)
        ) +
  # changing tick labels
  scale_y_continuous(labels = c("ESBL-/CPE-","ESBL+/CPE-","CPE+"),breaks = c(1, 2, 3))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/pie_all_sts.jpeg",
       width=8,
       height=4)
```
# figure: genomic resistance profiles and virulence scores by ST, top 7 STs only
```{r}
# seven most common STs
data<-
char_genomes_c %>%
#View()
  # selecting columns of interest
  select(iuc_locus:peg344_locus, resistance_profile, ST) %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
#View()
  # filter for top 7 STs
  filter(ST %in% top7STs) %>%
  # counting score combinations
  group_by(virulence_score, resistance_profile) %>%
  mutate(count=n()) %>%
  ungroup() %>%
#View()
  # calculating proportions
  group_by(virulence_score,resistance_profile,ST) %>% 
  mutate(prop = n()/count) %>%
  ungroup() %>%
  distinct() %>%
  # pivoting data wider
  pivot_wider(names_from=ST,
              values_from=prop) %>%
  select(-count) %>%
  # reordering rows
  arrange(virulence_score) %>%
  # indexing rows
  mutate(label=row_number()) %>%
  # replacing NA values with 0s
  mutate_all(~replace_na(.,0))

data2<-
char_genomes_c   %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))  %>%
#View()
  # selecting columns of interest
  select(iuc_locus:peg344_locus, resistance_profile, ST) %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
  select(virulence_score,resistance_profile,ST) %>%
  # filter for top 7 STs
  filter(ST %in% top7STs) %>%
  # counting score combinations
  group_by(virulence_score,resistance_profile) %>%
  mutate(count=n()) %>%
  select(virulence_score,resistance_profile,count) %>%
  distinct() %>%
  arrange(virulence_score)

data<-data %>%
  # left joining with count data
  left_join(data2,
            by=c("virulence_score","resistance_profile")) %>%
  # reordering columns
  select(virulence_score,
         resistance_profile,
         ST15,
         ST37,
         ST307,
         ST133,
         ST23,
         ST13,
         ST147,
         label,
         count)

#install.packages("scatterpie")
library(scatterpie)

# arbitrary function to define radius
min_x <- 1
max_x <- 25
to_min <- 0.02
to_max <- 0.5

# creating scaling function
scale_values <- function(x, min_x, max_x, to_min, to_max) {
  to_min + (x - min_x) * (to_max - to_min) / (max_x - min_x)
}

# applying scaling function to count values
data$radius <- scale_values(data$count, min_x, max_x, to_min, to_max)

#View()
ggplot() +
  geom_scatterpie(data=data,
                  aes(y=as.numeric(resistance_profile),
                      x=as.numeric(virulence_score),
                      group=label,
                      r=radius),
                  color=NA,
                  cols=colnames(data)[3:9],
                  alpha=0.8) + 
  coord_equal() +
  geom_label(data=data,
             aes(y=(as.numeric(resistance_profile)+radius+0.08),
                 x=(as.numeric(virulence_score)),
                label=paste0("n=",count)),
                size=3,
             label.padding = unit(0.15, "lines")) +
  theme_bw() +
  ylab("Genomic Resistance Profile") +
  # removing decimals on y axis
  scale_y_continuous(breaks = 0:3) +
  xlab("HvKp Marker Count") +
  labs(fill="ST")  +
  scale_fill_manual(labels = c("ST15 (n=24)",
                               "ST37 (n=20)",
                               "ST307 (n=19)",
                               "ST133 (n=14)",
                               "ST23 (n=10)",
                               "ST13 (n=11)",
                               "ST147 (n=8)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  #ggtitle("(b)") +
  # changing tick labels
  scale_y_continuous(labels = c("ESBL-/CPE-","ESBL+/CPE-","CPE+"),breaks = c(1, 2, 3))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/pie_top_sts.jpeg",
       width=8,
       height=4)
```
# supplementary figure: mean resistance scores and virulence scores by ST
```{r}
char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # defining top7STs column
  mutate(top7STs = if_else(ST %in% top7STs, ST, "Other STs (n=245)"))   %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
  group_by(top7STs) %>%
  summarise(n=n(),
            mean_rs=mean(resistance_score),
            mean_vs=mean(virulence_score)) %>%
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(top7STs=fct_relevel(top7STs,c("ST15",
                                       "ST37",
                                       "ST307",
                                       "ST133",
                                       "ST23",
                                       "ST13",
                                       "ST147",
                                       "Other STs (n=245)"))) %>%
#View()
  ggplot(aes(x=mean_vs,
             y=mean_rs)) +
  geom_point(aes(size=n,
                 colour=top7STs),
             alpha=0.8) +
  scale_size_continuous(
    range = c(2, 15),  # min/max size of bubbles
    breaks = c(1, 10, 50, 100, 200, 250),  # control which sizes appear in legend
    labels = c("1","10", "50", "100", "200", "250"),
    name = "Genome Count") +
  theme_bw() +
  labs(x="Mean HvKP Marker Count",
       y="Mean Resistance Score",
       #size="Number of Genomes",
       colour=NULL) +
  guides(size=F) +
  # removing decimals on y axis
  scale_y_continuous(breaks = 0:2) +
  scale_x_continuous(breaks = 0:5) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        #legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)
        ) +
  scale_colour_manual(labels = c("ST15 (n=24)",
                               "ST37 (n=20)",
                               "ST307 (n=19)",
                               "ST133 (n=14)",
                               "ST23 (n=10)",
                               "ST13 (n=11)",
                               "ST147 (n=8)",
                               "Other STs (n=245)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080"))
  
ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/mean_pies.jpeg",
       width=8,
       height=3)  
```
# description: resistance scores across collection months
```{r}
# mean resistance scores overall all STs
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    top7STs
    ) %>%
  summarise(mean=mean(resistance_score))

# monthly mean resistance scores
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    top7STs
    ) %>%
  summarise(mean=mean(resistance_score)) %>%
  arrange(desc(mean))

# mean resistance scores overall top STs
char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs)  %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    ST
    ) %>%
  summarise(mean=mean(resistance_score),
            max=max(resistance_score),
            min=min(resistance_score),
            range=max(resistance_score)-min(resistance_score)) %>%
  arrange(desc(mean))

```
# supplementary figure: resistance scores across collection months - all STs
```{r}
#char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  #filter(isolate_code %!in% c(# 2022 isolates
                              #"KLEB389",
                              #"KLEB391",
                              # duplicates
                              #"KLEB38",
                              #"KLEB98",
                              #"KLEB341")) %>%
  # defining top7STs column
  #mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs (n=103)", "Other STs (n=248)")) %>%
  #select(virulence_score,resistance_score,top7STs,`collect dt`) %>%
  # refactoring top7STs
  #mutate(top7STs=as.factor(top7STs)) %>%
  #group_by(month = lubridate::floor_date(`collect dt`, "month"),top7STs,resistance_score) %>%
  #tally() %>%
  #ggplot(aes(x=month,
             #y=top7STs,
             #size=n,
             #colour=top7STs,
             #shape=as.factor(resistance_score))) +
  #geom_jitter(alpha=0.8) +
  #xlab("Date") +
  #theme_bw() +
  #guides(size=F,colour=F,shape=guide_legend(title="Resistance Score")) +
  # dates aligned
  #scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  #scale_colour_manual(values = c("#008080","#FFA500")) +
  #scale_shape_manual(values = c(20,17,5,3,7,8)) +
  #theme(axis.title.x = element_blank(),
        #axis.title.y = element_blank(),
        # add legend box
        #legend.background=element_blank(), 
        # ensuring even legend border
        #legend.margin=margin(4,4,4,4, unit = "mm"),
        #legend.box.background=element_rect(colour = "black"),
        #plot.title = element_text(hjust = 0.5)) +
  #ggtitle("(a)") +
  # earliest date
  #geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             #linetype="dashed",
             #colour="#708090") +
  # latest date
  #geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             #linetype="dashed",
             #colour="#708090")

#a <- last_plot()

char_genomes_c   %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # defining top7STs column
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs (n=106)", "Other STs (n=245)")) %>%
  # refactoring top7STs
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    month = lubridate::floor_date(`collect dt`, "month"),
    top7STs
    ) %>%
  summarise(mean=mean(resistance_score),
            median=median(resistance_score),
            range=max(resistance_score)-min(resistance_score),
            min=min(resistance_score),
            max=max(resistance_score)) %>%
  #arrange(desc(mean))
  mutate(top7STs=fct_relevel(top7STs,c("Top 7 STs (n=106)", "Other STs (n=245)"))) %>%
  #arrange(desc(d))
  ggplot(aes(x=month, y=mean, colour=top7STs)) +
  geom_smooth(alpha=0.8) +
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.612,
                   yend = 0.612,),
               linetype="dashed",
               colour="#FFA500",
               size=0.3) +
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.181,
                   yend = 0.181),
               linetype="dashed",
               colour="#008080",
               size=0.3) +
  #geom_hline(yintercept = 0.612,linetype="dashed", colour="#FFA500", alpha=0.8, xl) +
  #geom_hline(yintercept = 0.181,linetype="dashed", colour="#008080", alpha=0.8) +
  theme_bw() +
  guides(size=F,colour=guide_legend(override.aes=list(fill=NA))) +
  ylab("Mean Resistance Score") +
  scale_y_continuous(limits = c(-1, 4), breaks = 0:3) +
  xlab("Date") +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_colour_manual(values = c("#FFA500","#008080")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/5_genotypic_resistance/resistance_STs_time.jpeg",
       width=8,
      height=3)
```
# description: virulence scores across collection months
```{r}
# mean virulence scores overall all STs
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    top7STs
    ) %>%
  summarise(mean=mean(virulence_score))

# monthly mean virulence scores
char_genomes_c %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c("KLEB389","KLEB391","KLEB098","KLEB341")) %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # characterising top 7 STs
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs", "Other STs")) %>%
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    top7STs
    ) %>%
  summarise(mean=mean(virulence_score)) %>%
  arrange(desc(mean))

# mean virulence scores overall top STs
char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs)  %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    ST
    ) %>%
  summarise(mean=mean(virulence_score),
            max=max(virulence_score),
            min=min(virulence_score),
            range=max(virulence_score)-min(virulence_score)) %>%
  arrange(desc(mean))
```
# supplementary figure: virulence scores across collection months - all STs
```{r}
#char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  #filter(isolate_code %!in% c(# 2022 isolates
                              #"KLEB389",
                              #"KLEB391",
                              # duplicates
                              ##"KLEB38",
                              #"KLEB98",
                              #"KLEB341")) %>%
  # defining top7STs column
  #mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs (n=103)", "Other STs (n=248)")) %>%
  # selecting columns of interest
  #select(virulence_score,resistance_score,top7STs,`collect dt`) %>%
  # refactoring top7STs
  #mutate(top7STs=as.factor(top7STs)) %>%
  #group_by(month = lubridate::floor_date(`collect dt`, "month"),top7STs,virulence_score) %>%
  #tally() %>%
  #arrange(desc(n))
  #ggplot(aes(x=month,
             #y=top7STs,
             #size=n,
             #colour=top7STs,
             #shape=as.factor(virulence_score))) +
  #geom_jitter(alpha=0.8) +
  #xlab("Date") +
  #theme_bw() +
  #guides(size=F,colour=F,shape=guide_legend(title="Virulence Score")) +
  # dates aligned
  #scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  #scale_colour_manual(values = c("#008080","#FFA500")) +
  #scale_shape_manual(values = c(20,17,5,3,7,8)) +
  #theme(axis.title.x = element_blank(),
        #axis.title.y = element_blank(),
        # add legend box
        #legend.background=element_blank(), 
        # ensuring even legend border
        #legend.margin=margin(4,4,4,4, unit = "mm"),
        #legend.box.background=element_rect(colour = "black"),
        #plot.title = element_text(hjust = 0.5)) +
  #ggtitle("(a)") +
  # earliest date
  #geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             #linetype="dashed",
             #colour="#708090") +
  # latest date
  #geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             #linetype="dashed",
             #colour="#708090")

#a <- last_plot()

char_genomes_c  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # defining top7STs column
  mutate(top7STs = if_else(ST %in% top7STs, "Top 7 STs (n=106)", "Other STs (n=245)"))  %>%
  # modifying virulence score for this plot
  mutate(virulence_score = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
  # refactoring top7STs
  mutate(top7STs=as.factor(top7STs)) %>%
  group_by(
    d = lubridate::floor_date(`collect dt`, "month"),
    top7STs
    ) %>%
  summarise(mean=mean(virulence_score),
            median=median(virulence_score),
            range=max(virulence_score)-min(virulence_score),
            min=min(virulence_score),
            max=max(virulence_score)) %>%
  mutate(top7STs=fct_relevel(top7STs,c("Top 7 STs (n=106)", "Other STs (n=245)"))) %>%
  arrange(desc(d)) %>%
  ggplot(aes(x=d, y=mean, colour=top7STs)) +
  geom_smooth(alpha=0.8) +
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.8867,
                   yend = 0.8867,),
               linetype="dashed",
               colour="#FFA500",
               size=0.3) +
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.7265,
                   yend = 0.7265),
               linetype="dashed",
               colour="#008080",
               size=0.3) +
  #geom_hline(yintercept = 0.612,linetype="dashed", colour="#FFA500", alpha=0.8, xl) +
  #geom_hline(yintercept = 0.181,linetype="dashed", colour="#008080", alpha=0.8) +
  theme_bw() +
  guides(size=F,color=guide_legend(override.aes=list(fill=NA))) +
  ylab("Mean HvKp Marker Count") +
  scale_y_continuous(limits = c(-1, 6), breaks = 0:5) +
  xlab("Date") +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  scale_colour_manual(values = c("#FFA500","#008080")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  # 1st national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-03-24")),
             linetype="dashed",
             size = 0.3,
             colour="#708090") +
  # 2nd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2020-11-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")  +
  # 3rd national lockdown
  geom_vline(xintercept = as.numeric(as.Date("2021-01-05")),
             linetype="dashed",
             size = 0.3,
             colour="#708090")

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/6_virulence/virulence_STs_time.jpeg",
       width=8,
      height=3)
```

<<< OLD CODE BELOW HERE >>>

*resistance scores and virulence scores across collection months*
====================================================================================================================================
# figure: resistance scores across collection months - top 7 STs only
```{r}
char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST147",
                             "ST13",
                             "ST23",
                             "ST133",
                             "ST307",
                             "ST37",
                             "ST15"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs) %>%
  group_by(month = lubridate::floor_date(date, "month"),ST,resistance_score) %>%
  tally() %>%
  #arrange(desc(n))
  ggplot(aes(x=month,
             y=ST,
             size=n,
             colour=ST,
             shape=as.factor(resistance_score))) +
  geom_jitter(alpha=0.8) +
  xlab("Date") +
  theme_bw() +
  guides(size=F,colour=F,shape=guide_legend(title="Resistance Score")) +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  # reverse colour order for y axis
  scale_color_manual(values = c("#33b29f",
                                "#ea705d",
                                "#f5af98",
                                "#71c9dd",
                                "#9da6c3",
                                "#a6dace",
                                "#6376a0")) +
  scale_shape_manual(values = c(20,17,5,3,7,8)) +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ggtitle("(a)") +
  # earliest date
  geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             linetype="dashed",
             colour="#708090") +
  # latest date
  geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             linetype="dashed",
             colour="#708090")
a <- last_plot()

char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs)  %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    ST
    ) %>%
  summarise(mean=mean(resistance_score),
            range=max(resistance_score)-min(resistance_score),
            min=min(resistance_score),
            max=max(resistance_score)) %>%
  #arrange(desc(d))
  ggplot(aes(x=d, y=mean, colour=ST)) +
  geom_smooth(se=F,alpha=0.8) +
  #geom_hline(yintercept = 0.612,linetype="dashed", colour="#FFA500", alpha=0.8, xl) +
  #geom_hline(yintercept = 0.181,linetype="dashed", colour="#008080", alpha=0.8) +
  theme_bw() +
  guides(size=F) +
  ylab("Mean Resistance Score") +
  scale_y_continuous(limits = c(-1, 4), breaks = 0:3) +
  xlab("Date") +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  # reverse colour order for y axis
  scale_color_manual(values = c("#6376a0","#a6dace","#9da6c3","#71c9dd","#f5af98","#ea705d","#33b29f")) +
  #scale_colour_manual(values = c("#FFA500","#008080")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ggtitle("(b)") +
  # earliest date
  geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             linetype="dashed",
             colour="#708090") +
  # latest date
  geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             linetype="dashed",
             colour="#708090") +
  # ST15
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 1.08,
                   yend = 1.08,),
               linetype="dashed",
               colour="#6376a0",
               size=0.55) +
  # ST37
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.05,
                   yend = 0.05,),
               linetype="dashed",
               colour="#a6dace",
               size=0.55) +
  # ST307
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.889,
                   yend = 0.889,),
               linetype="dashed",
               colour="#9da6c3",
               size=0.55) +
  # ST133
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.214,
                   yend = 0.214,),
               linetype="dashed",
               colour="#71c9dd",
               size=0.55) +
  # ST23
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.3,
                   yend = 0.3,),
               linetype="dashed",
               colour="#f5af98",
               size=0.55) +
  # ST13
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.44,
                   yend = 0.44,),
               linetype="dashed",
               colour="#ea705d",
               size=0.55) +
  # ST147
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 1.22,
                   yend = 1.22,),
               linetype="dashed",
               colour="#33b29f",
               size=0.55) 

b <- last_plot()
p <- a / b

p <- p + plot_layout(widths = c(1,1),
                     height = c(4.2375,3),
                     design = "A\nB")
p

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/results/genomics/resistance_scores_across_time_top7_STs.jpeg",
       width=10,
       height=10)
```
# figure: virulence scores across collection months - top 7 STs only
```{r}
char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST147",
                             "ST13",
                             "ST23",
                             "ST133",
                             "ST307",
                             "ST37",
                             "ST15"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs) %>%
  group_by(month = lubridate::floor_date(date, "month"),ST,virulence_score) %>%
  tally() %>%
  #arrange(desc(n))
  ggplot(aes(x=month,
             y=ST,
             size=n,
             colour=ST,
             shape=as.factor(virulence_score))) +
  geom_jitter(alpha=0.8) +
  xlab("Date") +
  theme_bw() +
  guides(size=F,colour=F,shape=guide_legend(title="Virulence Score")) +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  # reverse colour order for y axis
  scale_color_manual(values = c("#33b29f",
                                "#ea705d",
                                "#f5af98",
                                "#71c9dd",
                                "#9da6c3",
                                "#a6dace",
                                "#6376a0")) +
  scale_shape_manual(values = c(20,17,5,7,8)) +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ggtitle("(a)") +
  # earliest date
  geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             linetype="dashed",
             colour="#708090") +
  # latest date
  geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             linetype="dashed",
             colour="#708090")
a <- last_plot()

char_genomes_c %>%
  # changing date format
  mutate(date=as.Date(date,format = "%d-%m-%Y")) %>%
  # selecting columns of interest
  select(virulence_score,resistance_score,ST,date) %>%
  # renaming STs
  mutate(ST = paste0("ST",ST)) %>%
  # reordering levels
  mutate(ST=as.factor(ST)) %>%
  mutate(ST=fct_relevel(ST,c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # characterising top 7 STs
  filter(ST %in% top7STs)  %>%
  group_by(
    d = lubridate::floor_date(date, "month"),
    ST
    ) %>%
  summarise(mean=mean(virulence_score),
            range=max(virulence_score)-min(virulence_score),
            min=min(virulence_score),
            max=max(virulence_score)) %>%
  ggplot(aes(x=d, y=mean, colour=ST)) +
  geom_smooth(se=F,alpha=0.8) +
  #geom_hline(yintercept = 0.612,linetype="dashed", colour="#FFA500", alpha=0.8, xl) +
  #geom_hline(yintercept = 0.181,linetype="dashed", colour="#008080", alpha=0.8) +
  theme_bw() +
  guides(size=F) +
  ylab("Mean Virulence Score") +
  scale_y_continuous(limits = c(-1, 6), breaks = 0:5) +
  xlab("Date") +
  # dates aligned
  scale_x_date(limits = as.Date(c("2020-01-01","2022-01-31")),date_breaks = "1 year", date_labels = "%Y") +
  # reverse colour order for y axis
  scale_color_manual(values = c("#6376a0","#a6dace","#9da6c3","#71c9dd","#f5af98","#ea705d","#33b29f")) +
  #scale_colour_manual(values = c("#FFA500","#008080")) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        plot.title = element_text(hjust = 0.5)) +
  ggtitle("(b)") +
  # earliest date
  geom_vline(xintercept = as.numeric(as.Date("2021-12-01")),
             linetype="dashed",
             colour="#708090") +
  # latest date
  geom_vline(xintercept = as.numeric(as.Date("2020-04-01")),
             linetype="dashed",
             colour="#708090") +
  # ST15
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.625,
                   yend = 0.625,),
               linetype="dashed",
               colour="#6376a0",
               size=0.55) +
  # ST37
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.25,
                   yend = 0.25,),
               linetype="dashed",
               colour="#a6dace",
               size=0.55) +
  # ST307
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.1111,
                   yend = 0.1111,),
               linetype="dashed",
               colour="#9da6c3",
               size=0.55) +
  # ST133
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 1.2142,
                   yend = 1.2142,),
               linetype="dashed",
               colour="#71c9dd",
               size=0.55) +
  # ST23
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 4.9,
                   yend = 4.9,),
               linetype="dashed",
               colour="#f5af98",
               size=0.55) +
  # ST13
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 1.444,
                   yend = 1.444,),
               linetype="dashed",
               colour="#ea705d",
               size=0.55) +
  # ST147
  geom_segment(aes(x = as.Date("2020-04-01"),
                   xend = as.Date("2021-12-01"),
                   y = 0.4444,
                   yend = 0.4444,),
               linetype="dashed",
               colour="#33b29f",
               size=0.55) 

b <- last_plot()
p <- a / b

p <- p + plot_layout(widths = c(1,1),
                     height = c(4.2375,3),
                     design = "A\nB")
p

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/results/genomics/virulence_scores_across_time_top7_STs.jpeg",
       width=10,
       height=10)
```
