Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Playing around with tidygraph, ggraph, and NetIndices to draw food webs
#see also
#load libraries
#get prey of some of my favorite crustaceans
int <- get_interactions_by_taxa(sourcetaxon=c('Carcinus maenas', "Homarus americanus", "Cancer borealis", "Cancer irroratus"), interactiontype=c('preysOn', "eats", "kills"))
#make it into a from-to data frame for easy graph making
int_dat <- int %>%
rename(to = "source_taxon_name",
from = "target_taxon_name") %>%
dplyr::select(from, to)
#make a tidygraph object
gr <- tbl_graph(edges = int_dat)
#need an adjacency matrix for NetIndices
sp <- gr %>% activate(nodes) %>% pull
edges <- gr %>% activate(edges) %>%
adj_mat <- matrix(rep(0, length(sp)^2), nrow = length(sp))
for(i in 1:nrow(edges)) adj_mat[edges$from[i], edges$to[i]] <- 1
#add trophic levels and x positions
gr <- gr %>%
activate(nodes) %>%
mutate(y = TrophInd(adj_mat)[,1],
x = runif(length(sp)))
ggraph(gr) +
geom_node_point() +
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.