1 - Data standardisation

Setup

# Clear environment
rm(list=ls())

# Set the working directory
setwd("C:/Users/vitor/OneDrive/Doutorado PPGCB/Networks/Jaguaribe")

# Load the relevant libraries
library(dplyr); library(reshape2); library(magrittr); library(stringr); library(igraph); library(ggnetwork); library(tidyverse); library(bipartite); library(centiserve); library(gridExtra)
## 
## Anexando pacote: 'dplyr'
## Os seguintes objetos são mascarados por 'package:stats':
## 
##     filter, lag
## Os seguintes objetos são mascarados por 'package:base':
## 
##     intersect, setdiff, setequal, union
## 
## Anexando pacote: 'igraph'
## Os seguintes objetos são mascarados por 'package:dplyr':
## 
##     as_data_frame, groups, union
## Os seguintes objetos são mascarados por 'package:stats':
## 
##     decompose, spectrum
## O seguinte objeto é mascarado por 'package:base':
## 
##     union
## Carregando pacotes exigidos: ggplot2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.5
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ lubridate::%--%()       masks igraph::%--%()
## ✖ tibble::as_data_frame() masks igraph::as_data_frame(), dplyr::as_data_frame()
## ✖ purrr::compose()        masks igraph::compose()
## ✖ tidyr::crossing()       masks igraph::crossing()
## ✖ tidyr::extract()        masks magrittr::extract()
## ✖ dplyr::filter()         masks stats::filter()
## ✖ dplyr::lag()            masks stats::lag()
## ✖ purrr::set_names()      masks magrittr::set_names()
## ✖ purrr::simplify()       masks igraph::simplify()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## Carregando pacotes exigidos: vegan
## 
## Carregando pacotes exigidos: permute
## 
## 
## Anexando pacote: 'permute'
## 
## 
## O seguinte objeto é mascarado por 'package:igraph':
## 
##     permute
## 
## 
## Carregando pacotes exigidos: lattice
## 
## This is vegan 2.6-6.1
## 
## 
## Anexando pacote: 'vegan'
## 
## 
## O seguinte objeto é mascarado por 'package:igraph':
## 
##     diversity
## 
## 
## Carregando pacotes exigidos: sna
## 
## Carregando pacotes exigidos: statnet.common
## 
## 
## Anexando pacote: 'statnet.common'
## 
## 
## Os seguintes objetos são mascarados por 'package:base':
## 
##     attr, order
## 
## 
## Carregando pacotes exigidos: network
## 
## 
## 'network' 1.18.2 (2023-12-04), part of the Statnet Project
## * 'news(package="network")' for changes since last version
## * 'citation("network")' for citation information
## * 'https://statnet.org' for help, support, and other information
## 
## 
## 
## Anexando pacote: 'network'
## 
## 
## Os seguintes objetos são mascarados por 'package:igraph':
## 
##     %c%, %s%, add.edges, add.vertices, delete.edges, delete.vertices,
##     get.edge.attribute, get.edges, get.vertex.attribute, is.bipartite,
##     is.directed, list.edge.attributes, list.vertex.attributes,
##     set.edge.attribute, set.vertex.attribute
## 
## 
## sna: Tools for Social Network Analysis
## Version 2.7-2 created on 2023-12-05.
## copyright (c) 2005, Carter T. Butts, University of California-Irvine
##  For citation information, type citation("sna").
##  Type help(package="sna") to get started.
## 
## 
## 
## Anexando pacote: 'sna'
## 
## 
## Os seguintes objetos são mascarados por 'package:igraph':
## 
##     betweenness, bonpow, closeness, components, degree, dyad.census,
##     evcent, hierarchy, is.connected, neighborhood, triad.census
## 
## 
##  This is bipartite 2.20.
##  For latest changes see versionlog in ?"bipartite-package". For citation see: citation("bipartite").
##  Have a nice time plotting and analysing two-mode networks.
## 
## 
## Anexando pacote: 'bipartite'
## 
## 
## O seguinte objeto é mascarado por 'package:vegan':
## 
##     nullmodel
## 
## 
## O seguinte objeto é mascarado por 'package:igraph':
## 
##     strength
## 
## 
## Carregando pacotes exigidos: Matrix
## 
## 
## Anexando pacote: 'Matrix'
## 
## 
## Os seguintes objetos são mascarados por 'package:tidyr':
## 
##     expand, pack, unpack
## 
## 
## 
## Anexando pacote: 'gridExtra'
## 
## 
## O seguinte objeto é mascarado por 'package:dplyr':
## 
##     combine

Loading and curating data

# Read in the the data on fish-parasite interactions
fp <- read.csv("Parasites/parasites_jag.csv", header = TRUE, sep = ";")

# Read in the the data on fish-prey interactions
fd <- read.csv("Diet/diet_jag.csv", header = TRUE, sep = ";")

# Separate out the data on the fish individuals (e.g., mass, length)
fish <- select(fp, id:portion, -date, -sampling)

# Separate out the abiotic condition data
abiotic <- select(fp, id, site, date, transposition, season, portion, temp:nitrito)

Standardise the interaction strengths for interactions

# Interactions need to be standardised for endo and ecto parasites separately
# as they will not interact with one another and occupy different niches

# Separate out the information on the parasites
parasites <- select(fp, id, species, transposition, season, portion, 
                    contracaecum.endo:dolops.ecto)

# Separate the endoparasites
endo <- dplyr::select(parasites, contracaecum.endo:neoechinorhynchus.endo)

# Separate the ectoparasites
ecto <- dplyr::select(parasites, c_dig_ect.ecto:dolops.ecto)

# Calculate the total abundances of ectoparasites 
parasites$ecto_sum <- rowSums(ecto)

# Calculate the total abundances of endoparasites
parasites$endo_sum <- rowSums(endo)

# Divide the diet contributions by the total to get a proportion (for endo parasites)
stand_endo_total <- parasites %>% mutate(across(contracaecum.endo:neoechinorhynchus.endo, ~ ./endo_sum))

# Divide the diet contributions by the total to get a proportion (for ecto parasites)
stand_ecto_total <- parasites %>% mutate(across(c_dig_ect.ecto:dolops.ecto, ~ ./ecto_sum))


#Remove the extra columns for endoparasites
stand_endo <- select(stand_endo_total, species, transposition, season, portion, 
                     contracaecum.endo:neoechinorhynchus.endo)

#Remove the extra columns for ectoparasites
stand_ecto <- select(stand_ecto_total, species, transposition, season, portion, 
                     c_dig_ect.ecto:dolops.ecto) 

# Convert the NAs to zeros as they were generated by dividing 0 by 0 for endo and ecto 
stand_endo[is.na(stand_endo)] <- 0
stand_ecto[is.na(stand_ecto)] <- 0

# Convert the variables to factors for endoparasites
stand_endo$species <- as.factor(stand_endo$species)
stand_endo$transposition <- as.factor(stand_endo$transposition)
stand_endo$season <- as.factor(stand_endo$season)
stand_endo$portion <- as.factor(stand_endo$portion)

# Convert the variables to factors for ectoparasites
stand_ecto$species <- as.factor(stand_ecto$species)
stand_ecto$transposition <- as.factor(stand_ecto$transposition)
stand_ecto$season <- as.factor(stand_ecto$season)
stand_ecto$portion <- as.factor(stand_ecto$portion)

#Select the columns to use with the mean information
fp_endo_mean <- aggregate(. ~ species + transposition + season + portion,
                          data = stand_endo,
                          function(x) mean(x, na.rm = TRUE))

fp_ecto_mean <- aggregate(. ~ species + transposition + season + portion, 
                          data = stand_ecto, 
                          function(x) mean(x, na.rm = T))
#Select the data to extract the mean 
diet <- dplyr::select(fd, ephemeroptera:arachnida)
fd$diet_sum <- rowSums(diet)


# Divide the diet contributions by the total to get a proportion
stand_diet_total <- fd %>%
  mutate(across(ephemeroptera:arachnida, ~ ./diet_sum))

#Select the variables and prey information 
stand_diet <- stand_diet_total %>%
  select(species, season, transposition, portion, ephemeroptera:arachnida)

#Change the NAs to 0
stand_diet[is.na(stand_diet)] <- 0

#Generate a dataframe with the variables and mean values
fd_mean <- aggregate(. ~ species + season + transposition + portion, 
                     data = stand_diet, 
                     function(x) mean(x, na.rm = T))

# Convert the variables to factors
fd_mean$species <- as.factor(fd_mean$species)
fd_mean$season <- as.factor(fd_mean$season)
fd_mean$transposition <- as.factor(fd_mean$transposition)
fd_mean$portion <- as.factor(fd_mean$portion)


# Combine the dataframes for ecto and endo
df_parasites <- left_join(fp_endo_mean, fp_ecto_mean, 
                          by = c("species", "season", "transposition", "portion"))

# Combine the dataframes for parasites and variables
melted_par <- melt(df_parasites, id.vars = c("species", "season", "transposition", "portion"))

# Combine the dataframes for prey and variables
melted_diet <- melt(fd_mean, id.vars= c("species", "season", "transposition", "portion"))

Individual level networks

# Create the total edgelist for all interactions
edgelist <- bind_rows(melted_par, melted_diet, .id = "type")

# Recode 1s and 2s to be Parasitism and Predation
edgelist1 <- edgelist %>%
  mutate(type = ifelse(type == "1", "parasite", "prey"))

# Organize and recode the column names 
edgelist2 <- edgelist1 %>%
  select(species, variable, value, type, season, transposition, portion) %>%
  rename(fish = "species", inverts = "variable", weight = "value")

#Remove the interactions with the weight 0 (non-interaction)
edgelist3 <- subset(edgelist2, weight != 0)

#Turn inverts into character
edgelist3$fish <- as.character(edgelist3$fish)
edgelist3$inverts <- as.character(edgelist3$inverts)

# Create a dataframe for the nodes where all the fish species, parasite and prey information, 
# changing columns names to "fish", "parasite" and prey"
nodes <- data.frame(node = c(unique(edgelist3$fish), unique(edgelist3$inverts)),
                    type = c(rep("fish", length(unique(edgelist3$fish))),
                             rep("parasite", length(unique(melted_par$variable))),
                             rep("prey", length(unique(melted_diet$variable)))))


# Extract information on endo or ecto parasites to the nodes
nodes$para_type <- str_split(nodes$node, pattern = "\\.")

# Annotate
nodes$para_type_modified <- rep(NA, nrow(nodes))


nodes$para_type_modified <- ifelse(grepl("endo", nodes$para_type, ignore.case=T),
                                   "endo",
                                   nodes$para_type_modified)


nodes$para_type_modified <- ifelse(grepl("ecto", nodes$para_type,  ignore.case=T),
                                   "ecto",  
                                   nodes$para_type_modified)

# Remove endo and ecto information after dot in the nodes names
nodes$node <- sub("\\..*", "", nodes$node)

# Extract information on endo or ecto parasites to the edgelist
edgelist3$inverts_type <- str_split(edgelist3$inverts, pattern = "\\.")

# Remove endo and ecto information after dot in the nodes names
edgelist3$inverts <- sub("\\..*", "", edgelist3$inverts)

# Change the fish types to native and invasive
nodes1 <- nodes %>%
  mutate(fish_type = case_when(
    node %in% c("a_ocellatus", "s_dissimilis", "c_monoculus", "o_niloticus") ~ "non-native",
    TRUE ~ "native"))

# Creating a new column with all the information extracted and removing extras
nodes1$type_modified <- ifelse(nodes1$type == "fish", nodes1$fish_type, nodes1$para_type_modified)

# Removing unnecessary columns both on nodes1 and on edgelist3
nodes1$para_type <- NULL
nodes1$para_type_modified <- NULL
nodes1$fish_type <- NULL
edgelist3$inverts_type <- NULL

# Repeating the information of "prey" on type modified column 
nodes1[nodes1$type == "prey", "type_modified"] <- "prey"

2 - Bipartite network analysis

2.1 Fish-parasite interactions

# Change information on type column of edgelist3
edgelist_org <- edgelist3 %>%
  mutate(type = ifelse(type == 1, "parasite", "prey"))

# Select only the fish-parasites interactions
edgelist_par <- subset(edgelist3, type == "parasite")

# Convert variables into characters
edgelist_par$season <- as.character(edgelist_par$season)
edgelist_par$transposition <- as.character(edgelist_par$transposition)
edgelist_par$portion <- as.character(edgelist_par$portion)

# Rename column from "inverts" to "parasite"
edgelist_par <- rename(edgelist_par, parasite=inverts)

# Organise the fish and parasite nodes and rename columns from "inverts" to "parasite"
nodes_par <- data.frame(node = c(unique(as.character(edgelist_par$fish)), unique(as.character(edgelist_par$parasite))),
                        type = c(rep("fish", length(unique(edgelist_par$fish))),
                                 rep("parasite", length(unique(edgelist_par$parasite)))))

# Prepare the nodes coordinates
nodes_par[nodes_par$type == "fish", "x.coord"] <- seq(0, 1, length.out = sum(nodes_par$type == "fish"))
nodes_par[nodes_par$type == "parasite", "x.coord"] <- seq(0, 1, length.out = (sum(nodes_par$type == "parasite")))

nodes_par[nodes_par$type == "fish", "y.coord"] <- 0
nodes_par[nodes_par$type == "parasite", "y.coord"] <- 1

# Define the layout
lay_par <-as.matrix(nodes_par[, c("x.coord", "y.coord")])

# Create a list of edgelists for each variable (season, transposition and portion)
split_edgelists_par <- split(edgelist_par, interaction(edgelist_par$season, edgelist_par$transposition, edgelist_par$portion))

# A function to subset the nodes from the edgelists
node_subset_par <- function(x){
   fish_names <- unique(x$fish)
   parasite_names <- unique(x$parasite)
   taxon_list <- unique(c(fish_names, parasite_names)) 
   subset_y <- nodes_par[nodes_par$node %in% taxon_list,] 
  return(subset_y)
}

# Create a list of nodes for the networks
split_nodes_par <- lapply(split_edgelists_par, node_subset_par)

# Create bipartite networks for all of the nodes and edges 
##### When "directed = T" the Katz's results are different but the plot in bipartite works
bipartite_par_nets <- mapply(function(x,y){graph_from_data_frame(x, vertices = y, directed = F)}, 
                             x = split_edgelists_par, y = split_nodes_par)

# Create a function to label nodes depending on their 'type' - for bipartite graph plots
create_ind_type <- function(x, y){
  y$fish[is.na(y$fish)] <- "unknown"
  y$parasite[is.na(y$parasite)] <- "unknown"
  V(x)$type <- c(rep("fish",length(unique(y$fish))),rep("parasite",length(unique(y$parasite))))
  return(x)
}

# Add a variable 'type' to the vertex properties
individual_net_list <- mapply(create_ind_type, x = bipartite_par_nets, y = split_edgelists_par, SIMPLIFY = F)

## Convert the edgelists to matrices for bipartite analyses
df_parasites2 <- df_parasites

cleaned_colnames <- sub("\\..*", "", colnames(df_parasites2))

colnames(df_parasites2) <- cleaned_colnames
  
split_matrices_par <- split(df_parasites2, interaction(df_parasites2$season, df_parasites2$transposition, df_parasites2$portion))

# Create function to clean the matrices
m_cleaner <- function(x) {
  rownames(x) <- x$species
  x1 <- select(x, -season, -species, -transposition, -portion)
  return(x1)
}

# Prepare matrix to calculate the metrics
split_matrices1 <- lapply(split_matrices_par, m_cleaner)

Calculate the metrics for Parasites

# Create a dataframe to visualize the results
para_net_metrics <- data.frame(Site=rep(c("upper","middle","lower"), 4), 
                                          Season=c(rep("dry", 6),rep("wet", 6)),
                               Transposition = c(rep("post",6), rep("pre", 6)))

Network level

# Create a column on the dataframe to show results
para_net_metrics$Connectance <- NA

# Apply the function to show the Connectance values
para_net_metrics$Connectance <- unlist(lapply(split_matrices1, function(x){networklevel(x, index = "weighted connectance")}))
para_net_metrics$Nestedness <- NA
para_net_metrics$Nestedness <- unlist(lapply(split_matrices1, function(x){networklevel(x, index = "NODF")}))

Organise the results

# Function to extract names from matrices
species_names <- function(x){
  x1 <- x
  x2 <- bipartite::empty(x1)
  names<- c(colnames(x2),rownames(x2))
  return(names)
}

# List of species across sites
species_names_list <- lapply(split_matrices1, species_names)

# Dataframe for individual metrics
para_node_metrics <- data.frame(ID = unlist(species_names_list), 
                                     Season = substr(names(unlist(species_names_list)), 1, 3),
                                     Transposition = substr(names(unlist(species_names_list)), 5, 7), 
                                     Portion = substr(names(unlist(species_names_list)), 10, 12))


#Extract fish species for the Type column
species_fish <- unique(fish$species)

#Create Type column
para_node_metrics$Type <- NA

#Apply "Fish" and "Parasite" on Type column 
for (i in 1:nrow(para_node_metrics)) {
  if (para_node_metrics$ID[i] %in% species_fish) {para_node_metrics$Type[i] <- "fish"} else 
    {para_node_metrics$Type[i] <- "parasite"}
}

#Reorganize columns
para_node_metrics <- para_node_metrics[, c("ID", "Type", "Season", "Transposition", "Portion")]

Calculate the node-based values

para_node_metrics$Degree <- NA
para_node_metrics$Degree <- unlist(lapply(split_matrices1, function(x){specieslevel(x, index = "degree")}))
para_node_metrics$Katz <- NA
para_node_metrics$Katz <- unlist(lapply(bipartite_par_nets, function(x){katzcent(x)}))

2.2 Fish-prey interactions

## Organise the fish-prey edgelist
# Select only the fish-prey interactions
edgelist_prey <- subset(edgelist3, type == "prey")

# Convert variables into characters
edgelist_prey$season <- as.character(edgelist_prey$season)
edgelist_prey$transposition <- as.character(edgelist_prey$transposition)
edgelist_prey$portion <- as.character(edgelist_prey$portion)

# Rename column from "inverts" to "prey"
edgelist_prey <- rename(edgelist_prey, prey = inverts)

# Organise the fish and prey nodes 
nodes_prey <- data.frame(node = c(unique(edgelist_prey$fish), unique(as.character(edgelist_prey$prey))),
                         type = c(rep("fish", length(unique(edgelist_prey$fish))),
                                  rep("prey", length(unique(edgelist_prey$prey)))))

# Prepare the nodes coordinates
nodes_prey[nodes_prey$type == "fish", "x.coord"] <- seq(0, 1, length.out = sum(nodes_prey$type == "fish"))
nodes_prey[nodes_prey$type == "prey", "x.coord"] <- seq(0, 1, length.out = (sum(nodes_prey$type == "prey")))

nodes_prey[nodes_prey$type == "fish", "y.coord"] <- 0
nodes_prey[nodes_prey$type == "prey", "y.coord"] <- 1

lay_prey <-as.matrix(nodes_prey[, c("x.coord", "y.coord")])

# Create a list of edgelists for each variable (site, season and transposition)
split_edgelists_prey <- split(edgelist_prey, interaction(edgelist_prey$season, 
                                                         edgelist_prey$transposition, 
                                                         edgelist_prey$portion))

# A function to subset the nodes from the edgelists
node_subset_prey <- function(x){
  fish_names <- unique(x$fish)
  prey_names <- unique(x$prey)
  taxon_list <- unique(c(fish_names, prey_names)) 
  subset_y <- nodes_prey[nodes_prey$node %in% taxon_list,] 
  return(subset_y)
}


# Create a list of nodes for the networks
split_nodes_prey <- lapply(split_edgelists_prey, node_subset_prey)

# Create bipartite networks for all of the nodes and edges
bipartite_prey_nets <- mapply(function(x,y){graph_from_data_frame(x, vertices = y, directed = F)}, x = split_edgelists_prey, y = split_nodes_prey)

# Convert the edgelists to matrices for bipartite analyses
split_matrices_prey <- split(fd_mean, interaction(fd_mean$season, fd_mean$transposition, fd_mean$portion))

# Prepare matrix to calculate the metrics
split_matrices_prey1 <- lapply(split_matrices_prey, m_cleaner)

Calculate the metrics for Prey

# Create a dataframe to visualize the results
prey_net_metrics <- data.frame(Site=rep(c("upper","middle","lower"), 4), 
                               Season=c(rep("dry", 6),rep("wet", 6)),
                               Transposition = c(rep("post",6), rep("pre", 6)))
# Create a column on the dataframe to show results
prey_net_metrics$Connectance <- NA

# Apply the function to show the Connectance values
prey_net_metrics$Connectance <- unlist(lapply(split_matrices_prey1, function(x){networklevel(x, index = "weighted connectance")}))
prey_net_metrics$Nestedness <- NA
prey_net_metrics$Nestedness <- unlist(lapply(split_matrices_prey1, function(x){networklevel(x, index = "NODF")}))

Organise the resuls

# Function to extract names from matrices
species_names <- function(x){
  x1 <- x
  x2 <- bipartite::empty(x1)
  names<- c(colnames(x2),rownames(x2))
  return(names)
}

# List of species across sites
species_names_list <- lapply(split_matrices1, species_names)

# Apply the function to list species across sites
species_names_prey <- lapply(split_matrices_prey1, species_names)

# Dataframe for individual metrics
prey_node_metrics <- data.frame(ID = unlist(species_names_prey), 
                                Season = substr(names(unlist(species_names_prey)), 1, 3),
                                Transposition = substr(names(unlist(species_names_prey)), 5, 7),
                                Portion = substr(names(unlist(species_names_prey)), 10, 12))

#Extract fish species for the Type column
species_fish <- unique(fish$species)

#Create Type column
prey_node_metrics$Type <- NA

#Apply "Fish" and "Prey" on Type column 
for (i in 1:nrow(prey_node_metrics)) {
  if (prey_node_metrics$ID[i] %in% species_fish) {prey_node_metrics$Type[i] <- "fish"} else 
  {prey_node_metrics$Type[i] <- "prey"}
}

#Reorganize columns
prey_node_metrics <- prey_node_metrics[, c("ID", "Type", "Season", "Transposition", "Portion")]

Calculate the node-based values

prey_node_metrics$Degree <- NA
prey_node_metrics$Degree <- unlist(lapply(split_matrices_prey1, function(x){specieslevel(x, index = "degree")}))
prey_node_metrics$Katz <- NA
prey_node_metrics$Katz <- unlist(lapply(bipartite_prey_nets, function(x){katzcent(x)}))

3 - Network plotting

Tripartite plotting

# Create some x coordinates to use in plotting later
nodes1[nodes1$type == "fish", "x.coord"] <- seq(0, 1, length.out = sum(nodes1$type == "fish"))
nodes1[nodes1$type == "parasite", "x.coord"] <- seq(0, 1, length.out = (sum(nodes1$type == "parasite")))
nodes1[nodes1$type == "prey", "x.coord"] <- seq(0, 1, length.out = (sum(nodes1$type == "prey")))

# Create some y coordinates to use in plotting later
nodes1[nodes1$type == "fish", "y.coord"] <- 2
nodes1[nodes1$type == "parasite", "y.coord"] <- 3
nodes1[nodes1$type == "prey", "y.coord"] <- 1

# Adjust the height values
nodes1$height_adj <- (nodes1$y.coord - min(nodes1$y.coord)) / (max(nodes1$y.coord) - min(nodes1$y.coord))

Create the network graphs

edges_PRU <- subset(edgelist3, transposition == "pre" & portion == "upper")
graph_PRU <- graph_from_data_frame(edges_PRU, directed = T)
nodes_PRU <- nodes1[nodes1$node %in% c(unique(edges_PRU$fish), unique(edges_PRU$inverts)),]
lay_PRU <- as.matrix(nodes_PRU[, c("x.coord", "y.coord")])
network_PRU <-  ggnetwork:::fortify.igraph(graph_PRU, layout = lay_PRU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_PRU$height <- (nodes_PRU$y.coord - min(nodes_PRU$y.coord)) / (max(nodes_PRU$y.coord) - min(nodes_PRU$y.coord))

plot_PRU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_PRU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_PRU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Pre-transposition (Upper)")

plot_PRU

edges_PRM <- subset(edgelist3, transposition == "pre" & portion == "middle")
graph_PRM <- graph_from_data_frame(edges_PRM, directed = T)
nodes_PRM <- nodes1[nodes1$node %in% c(unique(edges_PRM$fish), unique(edges_PRM$inverts)),]
lay_PRM <- as.matrix(nodes_PRM[, c("x.coord", "y.coord")])
network_PRM <-  ggnetwork:::fortify.igraph(graph_PRM, layout = lay_PRM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_PRM$height <- (nodes_PRM$y.coord - min(nodes_PRM$y.coord)) / (max(nodes_PRM$y.coord) - min(nodes_PRM$y.coord))

plot_PRM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_PRM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_PRM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Pre-transposition (Middle)")

plot_PRM

edges_PRL <- subset(edgelist3, transposition == "pre" & portion == "lower")
graph_PRL <- graph_from_data_frame(edges_PRL, directed = T)
nodes_PRL <- nodes1[nodes1$node %in% c(unique(edges_PRL$fish), unique(edges_PRL$inverts)),]
lay_PRL <- as.matrix(nodes_PRL[, c("x.coord", "y.coord")])
network_PRL <-  ggnetwork:::fortify.igraph(graph_PRL, layout = lay_PRL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_PRL$height <- (nodes_PRL$y.coord - min(nodes_PRL$y.coord)) / (max(nodes_PRL$y.coord) - min(nodes_PRL$y.coord))

plot_PRL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_PRL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_PRL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Pre-transposition (Lower)")

plot_PRL

edges_POU <- subset(edgelist3, transposition == "post" & portion == "upper")
graph_POU <- graph_from_data_frame(edges_POU, directed = T)
nodes_POU <- nodes1[nodes1$node %in% c(unique(edges_POU$fish), unique(edges_POU$inverts)),]
lay_POU <- as.matrix(nodes_POU[, c("x.coord", "y.coord")])
network_POU <-  ggnetwork:::fortify.igraph(graph_POU, layout = lay_POU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_POU$height <- (nodes_POU$y.coord - min(nodes_POU$y.coord)) / (max(nodes_POU$y.coord) - min(nodes_POU$y.coord))

plot_POU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_POU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_POU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
 ggtitle("Post-transposition (Upper)")

plot_POU 

edges_POM <- subset(edgelist3, transposition == "post" & portion == "middle")
graph_POM <- graph_from_data_frame(edges_POM, directed = T)
nodes_POM <- nodes1[nodes1$node %in% c(unique(edges_POM$fish), unique(edges_POM$inverts)),]
lay_POM <- as.matrix(nodes_POM[, c("x.coord", "y.coord")])
network_POM <-  ggnetwork:::fortify.igraph(graph_POM, layout = lay_POM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_POM$height <- (nodes_POM$y.coord - min(nodes_POM$y.coord)) / (max(nodes_POM$y.coord) - min(nodes_POM$y.coord))

plot_POM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_POM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_POM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank() +
  ggtitle("Post-transposition (Middle)")

plot_POM

edges_POL <- subset(edgelist3, transposition == "post" & portion == "lower")
graph_POL <- graph_from_data_frame(edges_POL, directed = T)
nodes_POL <- nodes1[nodes1$node %in% c(unique(edges_POL$fish), unique(edges_POL$inverts)),]
lay_POL <- as.matrix(nodes_POL[, c("x.coord", "y.coord")])
network_POL <-  ggnetwork:::fortify.igraph(graph_POL, layout = lay_POL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_POL$height <- (nodes_POL$y.coord - min(nodes_POL$y.coord)) / (max(nodes_POL$y.coord) - min(nodes_POL$y.coord))

plot_POL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_POL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_POL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Post-transposition (Lower)")

plot_POL

grid_plot_tri <- grid.arrange(plot_PRU, plot_PRM, plot_PRL, plot_POU, plot_POM, plot_POL, nrow = 2)

# Save image 
#ggsave("C:/Users/Windows 10/OneDrive/Doutorado PPGCB/Networks/Jaguaribe/Results/Plots/Networks/Fish-parasite-prey_Transp_Port.png", 
#       plot = grid_plot_tri, 
#       dpi = 1200)

3.1 Bipartite plotting

edges_par_PRU <- subset(edgelist3, type == "parasite" & transposition == "pre" & portion == "upper")
graph_par_PRU <- graph_from_data_frame(edges_par_PRU, directed = T)
nodes_par_PRU <- nodes1[nodes1$node %in% c(unique(edges_par_PRU$fish), unique(edges_par_PRU$inverts)),]
lay_par_PRU <- as.matrix(nodes_par_PRU[, c("x.coord", "y.coord")])
network_par_PRU <-  ggnetwork:::fortify.igraph(graph_par_PRU, layout = lay_par_PRU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_PRU$height <- (nodes_par_PRU$y.coord - min(nodes_par_PRU$y.coord)) / (max(nodes_par_PRU$y.coord) - min(nodes_par_PRU$y.coord))

plot_par_PRU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_PRU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_PRU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank() +
  ggtitle("Parasites (Pre/Upper)")

plot_par_PRU

edges_par_PRM <- subset(edgelist3, type == "parasite" & transposition == "pre" & portion == "middle")
graph_par_PRM <- graph_from_data_frame(edges_par_PRM, directed = T)
nodes_par_PRM <- nodes1[nodes1$node %in% c(unique(edges_par_PRM$fish), unique(edges_par_PRM$inverts)),]
lay_par_PRM <- as.matrix(nodes_par_PRM[, c("x.coord", "y.coord")])
network_par_PRM <-  ggnetwork:::fortify.igraph(graph_par_PRM, layout = lay_par_PRM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_PRM$height <- (nodes_par_PRM$y.coord - min(nodes_par_PRM$y.coord)) / (max(nodes_par_PRM$y.coord) - min(nodes_par_PRM$y.coord))

plot_par_PRM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_PRM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_PRM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank()  +
  ggtitle("Parasites (Pre/Middle)")

plot_par_PRM

edges_par_PRL <- subset(edgelist3, type == "parasite" & transposition == "pre" & portion == "lower")
graph_par_PRL <- graph_from_data_frame(edges_par_PRL, directed = T)
nodes_par_PRL <- nodes1[nodes1$node %in% c(unique(edges_par_PRL$fish), unique(edges_par_PRL$inverts)),]
lay_par_PRL <- as.matrix(nodes_par_PRL[, c("x.coord", "y.coord")])
network_par_PRL <-  ggnetwork:::fortify.igraph(graph_par_PRL, layout = lay_par_PRL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_PRL$height <- (nodes_par_PRL$y.coord - min(nodes_par_PRL$y.coord)) / (max(nodes_par_PRL$y.coord) - min(nodes_par_PRL$y.coord))

plot_par_PRL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_PRL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_PRL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank()  +
  ggtitle("Parasites (Pre/Lower)")

plot_par_PRL

edges_par_POU <- subset(edgelist3, type == "parasite" & transposition == "post" & portion == "upper")
graph_par_POU <- graph_from_data_frame(edges_par_POU, directed = T)
nodes_par_POU <- nodes1[nodes1$node %in% c(unique(edges_par_POU$fish), unique(edges_par_POU$inverts)),]
lay_par_POU <- as.matrix(nodes_par_POU[, c("x.coord", "y.coord")])
network_par_POU <-  ggnetwork:::fortify.igraph(graph_par_POU, layout = lay_par_POU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_POU$height <- (nodes_par_POU$y.coord - min(nodes_par_POU$y.coord)) / (max(nodes_par_POU$y.coord) - min(nodes_par_POU$y.coord))

plot_par_POU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_POU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_POU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank()  +
  ggtitle("Parasites (Post/Upper)")

plot_par_POU

edges_par_POM <- subset(edgelist3, type == "parasite" & transposition == "post" & portion == "middle")
graph_par_POM <- graph_from_data_frame(edges_par_POM, directed = T)
nodes_par_POM <- nodes1[nodes1$node %in% c(unique(edges_par_POM$fish), unique(edges_par_POM$inverts)),]
lay_par_POM <- as.matrix(nodes_par_POM[, c("x.coord", "y.coord")])
network_par_POM <-  ggnetwork:::fortify.igraph(graph_par_POM, layout = lay_par_POM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_POM$height <- (nodes_par_POM$y.coord - min(nodes_par_POM$y.coord)) / (max(nodes_par_POM$y.coord) - min(nodes_par_POM$y.coord))

plot_par_POM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_POM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_POM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank()  +
  ggtitle("Parasites (Post/Middle)")

plot_par_POM

edges_par_POL <- subset(edgelist3, type == "parasite" & transposition == "post" & portion == "lower")
graph_par_POL <- graph_from_data_frame(edges_par_POL, directed = T)
nodes_par_POL <- nodes1[nodes1$node %in% c(unique(edges_par_POL$fish), unique(edges_par_POL$inverts)),]
lay_par_POL <- as.matrix(nodes_par_POL[, c("x.coord", "y.coord")])
network_par_POL <-  ggnetwork:::fortify.igraph(graph_par_POL, layout = lay_par_POL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_par_POL$height <- (nodes_par_POL$y.coord - min(nodes_par_POL$y.coord)) / (max(nodes_par_POL$y.coord) - min(nodes_par_POL$y.coord))

plot_par_POL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_par_POL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_par_POL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59")) +
  theme_blank()  +
  ggtitle("Parasites (Post/Lower)")

plot_par_POL

grid_plot_par <- grid.arrange(plot_par_PRU, plot_par_PRM, plot_par_PRL, plot_par_POU, plot_par_POM, plot_par_POL, nrow = 2)

# Save image 
#ggsave("C:/Users/Windows 10/OneDrive/Doutorado PPGCB/Networks/Jaguaribe/Results/Plots/Networks/Fish-parasite_Transp_Port.png", 
#       plot = grid_plot_par, 
#       dpi = 1200)
edges_prey_PRU <- subset(edgelist3, type == "prey" & transposition == "pre" & portion == "upper")
graph_prey_PRU <- graph_from_data_frame(edges_prey_PRU, directed = T)
nodes_prey_PRU <- nodes1[nodes1$node %in% c(unique(edges_prey_PRU$fish), unique(edges_prey_PRU$inverts)),]
lay_prey_PRU <- as.matrix(nodes_prey_PRU[, c("x.coord", "y.coord")])
network_prey_PRU <-  ggnetwork:::fortify.igraph(graph_prey_PRU, layout = lay_prey_PRU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_PRU$height <- (nodes_prey_PRU$y.coord - min(nodes_prey_PRU$y.coord)) / (max(nodes_prey_PRU$y.coord) - min(nodes_prey_PRU$y.coord))

plot_prey_PRU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_PRU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_PRU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Pre/Upper)")

plot_prey_PRU

edges_prey_PRM <- subset(edgelist3, type == "prey" & transposition == "pre" & portion == "middle")
graph_prey_PRM <- graph_from_data_frame(edges_prey_PRM, directed = T)
nodes_prey_PRM <- nodes1[nodes1$node %in% c(unique(edges_prey_PRM$fish), unique(edges_prey_PRM$inverts)),]
lay_prey_PRM <- as.matrix(nodes_prey_PRM[, c("x.coord", "y.coord")])
network_prey_PRM <-  ggnetwork:::fortify.igraph(graph_prey_PRM, layout = lay_prey_PRM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_PRM$height <- (nodes_prey_PRM$y.coord - min(nodes_prey_PRM$y.coord)) / (max(nodes_prey_PRM$y.coord) - min(nodes_prey_PRM$y.coord))

plot_prey_PRM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_PRM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_PRM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Pre/Middle)")

plot_prey_PRM

edges_prey_PRL <- subset(edgelist3, type == "prey" & transposition == "pre" & portion == "lower")
graph_prey_PRL <- graph_from_data_frame(edges_prey_PRL, directed = T)
nodes_prey_PRL <- nodes1[nodes1$node %in% c(unique(edges_prey_PRL$fish), unique(edges_prey_PRL$inverts)),]
lay_prey_PRL <- as.matrix(nodes_prey_PRL[, c("x.coord", "y.coord")])
network_prey_PRL <-  ggnetwork:::fortify.igraph(graph_prey_PRL, layout = lay_prey_PRL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_PRL$height <- (nodes_prey_PRL$y.coord - min(nodes_prey_PRL$y.coord)) / (max(nodes_prey_PRL$y.coord) - min(nodes_prey_PRL$y.coord))

plot_prey_PRL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_PRL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_PRL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Pre/Lower)")

plot_prey_PRL

edges_prey_POU <- subset(edgelist3, type == "prey" & transposition == "post" & portion == "upper")
graph_prey_POU <- graph_from_data_frame(edges_prey_POU, directed = T)
nodes_prey_POU <- nodes1[nodes1$node %in% c(unique(edges_prey_POU$fish), unique(edges_prey_POU$inverts)),]
lay_prey_POU <- as.matrix(nodes_prey_POU[, c("x.coord", "y.coord")])
network_prey_POU <-  ggnetwork:::fortify.igraph(graph_prey_POU, layout = lay_prey_POU, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_POU$height <- (nodes_prey_POU$y.coord - min(nodes_prey_POU$y.coord)) / (max(nodes_prey_POU$y.coord) - min(nodes_prey_POU$y.coord))

plot_prey_POU <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_POU) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_POU) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Post/Upper)")

plot_prey_POU

edges_prey_POM <- subset(edgelist3, type == "prey" & transposition == "post" & portion == "middle")
graph_prey_POM <- graph_from_data_frame(edges_prey_POM, directed = T)
nodes_prey_POM <- nodes1[nodes1$node %in% c(unique(edges_prey_POM$fish), unique(edges_prey_POM$inverts)),]
lay_prey_POM <- as.matrix(nodes_prey_POM[, c("x.coord", "y.coord")])
network_prey_POM <-  ggnetwork:::fortify.igraph(graph_prey_POM, layout = lay_prey_POM, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_POM$height <- (nodes_prey_POM$y.coord - min(nodes_prey_POM$y.coord)) / (max(nodes_prey_POM$y.coord) - min(nodes_prey_POM$y.coord))

plot_prey_POM <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_POM) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_POM) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                          "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Post/Middle)")

plot_prey_POM

edges_prey_POL <- subset(edgelist3, type == "prey" & transposition == "post" & portion == "lower")
graph_prey_POL <- graph_from_data_frame(edges_prey_POL, directed = T)
nodes_prey_POL <- nodes1[nodes1$node %in% c(unique(edges_prey_POL$fish), unique(edges_prey_POL$inverts)),]
lay_prey_POL <- as.matrix(nodes_prey_POL[, c("x.coord", "y.coord")])
network_prey_POL <-  ggnetwork:::fortify.igraph(graph_prey_POL, layout = lay_prey_POL, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_prey_POL$height <- (nodes_prey_POL$y.coord - min(nodes_prey_POL$y.coord)) / (max(nodes_prey_POL$y.coord) - min(nodes_prey_POL$y.coord))

plot_prey_POL <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_prey_POL) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 4.5, data = nodes_prey_POL) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "prey" = "#fee090")) +
  theme_blank()  +
  ggtitle("Prey (Post/Lower)")

plot_prey_POL

grid_plot_prey <- grid.arrange(plot_prey_PRU, plot_prey_PRM, plot_prey_PRL, plot_prey_POU, plot_prey_POM, plot_prey_POL, nrow = 2)

# Save image 
#ggsave("C:/Users/Windows 10/OneDrive/Doutorado PPGCB/Networks/Jaguaribe/Results/Plots/Networks/Fish-prey_Transp_Port.png", 
#       plot = grid_plot_prey, 
#       dpi = 1200)
edges_transp_pre <- subset(edgelist3, transposition == "pre")
graph_transp_pre <- graph_from_data_frame(edges_transp_pre, directed = T)
nodes_transp_pre <- nodes1[nodes1$node %in% c(unique(edges_transp_pre$fish), unique(edges_transp_pre$inverts)),]
lay_transp_pre <- as.matrix(nodes_transp_pre[, c("x.coord", "y.coord")])
network_transp_pre <-  ggnetwork:::fortify.igraph(graph_transp_pre, layout = lay_transp_pre, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_transp_pre$height <- (nodes_transp_pre$y.coord - min(nodes_transp_pre$y.coord)) / (max(nodes_transp_pre$y.coord) - min(nodes_transp_pre$y.coord))

plot_transp_pre <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_transp_pre) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 6, data = nodes_transp_pre) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank() +
  ggtitle("Pre-transposition")

plot_transp_pre

edges_transp_post <- subset(edgelist3, transposition == "post")
graph_transp_post <- graph_from_data_frame(edges_transp_post, directed = T)
nodes_transp_post <- nodes1[nodes1$node %in% c(unique(edges_transp_post$fish), unique(edges_transp_post$inverts)),]
lay_transp_post <- as.matrix(nodes_transp_post[, c("x.coord", "y.coord")])
network_transp_post <-  ggnetwork:::fortify.igraph(graph_transp_post, layout = lay_transp_post, scale = F )
## Warning in format_fortify(model = model, nodes = nodes, weights = "none", :
## duplicated edges detected
nodes_transp_post$height <- (nodes_transp_post$y.coord - min(nodes_transp_post$y.coord)) / (max(nodes_transp_post$y.coord) - min(nodes_transp_post$y.coord))

plot_transp_post <- ggplot() +
  geom_edges(alpha = 0.2, aes(x = xend, y = yend, xend = x, yend = y), data = network_transp_post) +
  geom_nodes(aes(x = x.coord, y = y.coord, shape = factor(type), colour = factor(type_modified)), size = 6, data = nodes_transp_post) +
  #geom_label(data = nodes1, aes(x = x.coord, y = height, label = node), inherit.aes = F) +
  scale_shape_manual(guide = "none", values = c("fish" = 16, "parasite" = 17, "prey" = 15)) +
  scale_size_manual(guide = "none", values = c(10,8, 9)) +
  scale_colour_manual(guide = "none", name = "", values = c("non-native" = "#91bfdb", "native" = "#4575b4", 
                                                            "ecto" = "#d73027", "endo" = "#fc8d59", 
                                                            "prey" = "#fee090")) +
  theme_blank() +
  ggtitle("Post-transposition")

plot_transp_post

grid_plot_transp <- grid.arrange(plot_transp_pre, plot_transp_post, nrow = 1)

# Save image 
#ggsave("C:/Users/Windows 10/OneDrive/Doutorado PPGCB/Networks/Jaguaribe/Results/Plots/Networks/Fish-parasite-prey_Transp.png", 
#       plot = grid_plot_transp, 
#       dpi = 1200)

4 - Metrics plotting

# Organise the visualization
para_net_metrics$Transposition <- 
  factor(para_net_metrics$Transposition, levels = c("pre", "post"))
para_net_metrics$Site <- 
  factor(para_net_metrics$Site, levels = c("upper", "middle", "lower"))
ggplot(para_net_metrics) +
  aes(x = Transposition, y = Nestedness) +
  geom_boxplot(fill = "#112446") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(prey_net_metrics) +
  aes(x = Transposition, y = Connectance) +
  geom_boxplot(fill = "#112446") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(para_net_metrics) +
  aes(x = Transposition, fill = Site, weight = Connectance) +
  geom_bar(position = "dodge") +
  scale_fill_brewer(palette = "GnBu", direction = 1) +
  labs(title = "Connectance") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(para_net_metrics) +
  aes(x = Transposition, fill = Site, weight = Nestedness) +
  geom_bar(position = "dodge") +
  scale_fill_brewer(palette = "GnBu", direction = 1) +
  labs(title = "Nestedness") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

# Organise the visualization
prey_net_metrics$Transposition <- 
  factor(prey_net_metrics$Transposition, levels = c("pre", "post"))
prey_net_metrics$Site <- 
  factor(prey_net_metrics$Site, levels = c("upper", "middle", "lower"))
ggplot(prey_net_metrics) +
  aes(x = Transposition, y = Nestedness) +
  geom_boxplot(fill = "#112446") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(prey_net_metrics) +
  aes(x = Transposition, y = Connectance) +
  geom_boxplot(fill = "#112446") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(prey_net_metrics) +
  aes(x = Transposition, fill = Site, weight = Connectance) +
  geom_bar(position = "dodge") +
  scale_fill_brewer(palette = "GnBu", direction = 1) +
  labs(title = "Connectance") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))

ggplot(prey_net_metrics) +
  aes(x = Transposition, fill = Site, weight = Nestedness) +
  geom_bar(position = "dodge") +
  scale_fill_brewer(palette = "GnBu", direction = 1) +
  labs(title = "Nestedness") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20L, hjust = 0.5))