Categories
data science

Draw and Save Network to PDF – R

Assuming you start with a pajek file, you can use the following two functions to draw the graph and save it on to a PDF file.

# first you have to import the iGraph library
library(igraph)

# This first function will format the graph
draw.quick.graph <- function(g) {
    plot(
        g,                                                     
        layout=layout.fruchterman.reingold,
        vertex.label=NA,
        vertex.size=2,
        vertex.color="white",
        vertex.frame.color="black",
        edge.width=1
    )
}

# This second function will ...
drawTheGraph <- function(loc){
    # ... read the pajek graph ...
	g <- read.graph(loc,format="pajek")
    # ... simplify it...
	sg <- simplify(g)
    # ...create the PDF file on the Desktop (Unix systems)...
	pdf("Desktop/output.pdf")
    # ...draw the graph using the above function...
	draw.quick.graph(sg)
    # ... close the file.
	dev.off()
}

Then you call the function like this

drawTheGraph("/path/to/the/pajek.net")

…and you get something like this

Copypasta for the lazy

library(igraph)
draw.quick.graph <- function(g) {
    plot(
        g,                                                     
        layout=layout.fruchterman.reingold,
        vertex.label=NA,
        vertex.size=2,
        vertex.color="white",
        vertex.frame.color="black",
        edge.width=1
    )
}

drawTheGraph <- function(loc){
	g <- read.graph(loc,format="pajek")
	sg <- simplify(g)
	pdf("Desktop/output.pdf")
	draw.quick.graph(sg)
	dev.off()
}

drawTheGraph("")

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s