Skip to content

Instantly share code, notes, and snippets.

@jebyrnes
Created May 14, 2019 21:24
Show Gist options
  • Save jebyrnes/cbfa6b92ab404cf10cb86b9df3f18ae0 to your computer and use it in GitHub Desktop.
Save jebyrnes/cbfa6b92ab404cf10cb86b9df3f18ae0 to your computer and use it in GitHub Desktop.
Playing around with tidygraph, ggraph, and NetIndices to draw food webs
#see also https://davidsmale.netlify.com/portfolio/wes-anderson-actor-network/
# https://www.data-imaginist.com/2017/introducing-tidygraph/
# https://www.jessesadler.com/post/network-analysis-with-r/
#load libraries
library(rglobi)
library(tidygraph)
library(ggraph)
library(NetIndices)
#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) %>% as.data.frame
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)))
#plot
ggraph(gr) +
geom_node_point() +
geom_edge_link0()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment