1
votes

I have a function that creates multiple network plots using the igraph package and stores the networks in a list (g.list is the final output).

The function looks like this - and uses a list of dataframes (nodes and edges) to create the networks.

 network.fun <- function(nodes, edges){

  g <- graph_from_data_frame(d = edges, vertices = nodes, directed = FALSE)

  V(g)$color <- ifelse(V(g)$Treatment == "Water", ff.1[3], ff.1[4])

  w1 <- rescale(E(g)$weight, to = c(0,10))

  m1 <- layout_nicely(g) 

  plot(g, vertex.label.color = "black",
                   edge.color = 'dark grey', edge.width = w1, 
                   layout = m1, vertex.size = 24, vertex.label.font=2, 
                   vertex.label.dist=2.3, vertex.label.degree=4.3)


  return(g)


}

g.list <- map(out.list, ~ network.fun(nodes = .x$nodes, edges = .x$edges)) 

I want to know if it is possible to save each plot as a png file as it is created. I have 108 plots that are created and so would also like the plots to be named according to the nodes/edges dataframe name used to create them.

1

1 Answers

1
votes

It doesn't look like you can save an igraph to an object, but you could save the plot directly by wrapping it in ggsave() like this:

 ggsave(paste0(plotName, ".png),
        plot(g, vertex.label.color = "black",
                       edge.color = 'dark grey', edge.width = w1, 
                       layout = m1, vertex.size = 24, vertex.label.font=2, 
                       vertex.label.dist=2.3, vertex.label.degree=4.3),
        height = 5, width = 5, dpi = 1000)

You can add a plotName argument to your function and define it with a string (e.g. plotName = "plot_1"): if you're mapping over out.list, you can use the names of out.list like this:

map2(out.list, names(out.list), ~ network.fun(plotName = .y, nodes = .x$nodes, edges = .x$edges))