Skip to content

Instantly share code, notes, and snippets.

@beemyfriend
Created September 6, 2018 04:41
Show Gist options
  • Save beemyfriend/2bfdcfbdd844cd952615cd09d6d2276c to your computer and use it in GitHub Desktop.
Save beemyfriend/2bfdcfbdd844cd952615cd09d6d2276c to your computer and use it in GitHub Desktop.
Playing with DAG communities by adding 1 edge at different places to a base DAG
library(igraph)
library(grid)
library(gridGraphics)
#### Make a base graph ####
g <- make_tree(15) +
edges(4, 7,
8, 14,
9, 10,
15, 13)
#### Confirm that it is a DAG ####
is_dag(g)
#### Bin each node into a community by using Walktrap ####
wc <- cluster_walktrap(g)
#### Layout of nodes to have a consistent layout for all variations of graph ####
l <- matrix(
c(1, 5,
2, 3,
2, 7,
3, 4.5,
4, 1,
4, 10,
3, 6.5,
5, 4.5,
4, 3,
5, 3,
5, 1,
5, 10,
5, 8,
5, 6.5,
4, 8),
ncol = 2,
byrow = T
)
#### Plotting defaults stored in nodes and edges ####
E(g)$label = ''
V(g)$label.font = 2
V(g)$label.cex = 1.5
V(g)$label.color = 'whitesmoke'
#### Plot and store graph into a grid object ####
plot(wc, g, layout = l, main = 'Starting DAG')
grid.echo()
a <- grid.grab()
#### Add an edge to the base graph ####
#### Create a grid object for the plot ####
#### Create a grid object for title (for some reason the "main" attribute of plot disappears ####
addEdgeToDAG <- function(g, e, l) {
new_g <- g + edge(e)
V(new_g)$label = ''
V(new_g)$size = 0
E(new_g)$label = ''
wc <- cluster_walktrap(new_g)
plot(wc, new_g, layout = l, main= paste0(e[1], ' -> ', e[2]))
}
grabbedPlots <- lapply(list(c(4, 5), c(3, 15), c(14, 13)), function(x){
addEdgeToDAG(g, x, l)
grid.echo()
temp <- grid.grab()
list(plot = temp, text = textGrob(paste0(x[1], ' -> ', x[2]), x = .5, y = .85))
})
png('walktrap_play.png', width = 600, height = 450)
grid.newpage()
pushViewport(viewport(x = .33, y = .5, width=.66, height= 1))
grid.draw(a)
grid.draw(textGrob("Exploring Changes to DAG Walktrap Community\nBy Adding Only 1 New Edge",x = .5, y = .1))
popViewport()
pushViewport(viewport(x = 1 - .2, y = 1 - .15, width=.32, height=.32))
grid.draw(grabbedPlots[[3]]$plot)
grid.draw(grabbedPlots[[3]]$text)
popViewport()
pushViewport(viewport(x = 1 - .2, y = .5, width=.32, height=.32))
grid.draw(grabbedPlots[[1]]$plot)
grid.draw(grabbedPlots[[1]]$text)
popViewport()
pushViewport(viewport(x = 1 - .2, y = .15, width=.32, height=.32))
grid.draw(grabbedPlots[[2]]$plot)
grid.draw(grabbedPlots[[2]]$text)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment