Basic Workflow 2: Working with igraph

by Kazuhiro Takemoto*

Updated by Keiichiro Ono

(The original tutorial was developed by Dr. Takemoto, and updated by Keiichiro Ono for cy-rest.)


Introduction

Welcome to part 2 of the R tutorial. In this section, you will learn how to use Cytoscape with igraph.

What is igraph?

igraph is one of the most popular network analysis toolkits for R/Python/C. It has a lot of graph analysis algorithms and utilities that Cytoscape does not have. If you use Cytoscape from igraph, you can use variety of network analysis functions in igraph and visualize the result with powerful visualization tools available in Cytoscape.

# Basic setup
library(igraph)
library(RJSONIO)
library(httr)

port.number = 1234
base.url = paste("http://localhost:", toString(port.number), "/v1", sep="")
print(base.url)
## [1] "http://localhost:1234/v1"

Loading Networks

There are many ways to import network data into igraph. In this example, let’s try to load text data as Data Frame, and then convert it into igraph object.

# Load list of edges as Data Frame
network.df <- read.table("data/eco_EM+TCA.txt")

# Convert it into igraph object
network <- graph.data.frame(network.df,directed=T)

# Remove duplicate edges & loops
g.tca <- simplify(network, remove.multiple=T, remove.loops=T)

# Name it
g.tca$name = "Ecoli TCA Cycle"

Convert igraph object into JSON

As you learned in the first tutorial, basic data exchange format between Cytoscape and external tools is Cytoscape.js JSON. To send igraph object to Cytoscape, you need to convert it into JSON:

# This function will be published as a part of utility package, but not ready yet.
source('toCytoscape.R')

# Convert it into Cytosccape.js JSON
cygraph <- toCytoscape(g.tca)

Visualize it in Cytoscape

Now you are ready to visualize your data in Cytoscape. It’s very straightforward:

send2cy <- function(cygraph) {
  network.url = paste(base.url, "networks", sep="/")
  res <- POST(url=network.url, body=cygraph, encode="json")
  network.suid = unname(fromJSON(rawToChar(res$content)))
  print(network.suid)
  
  # Apply Visual Style and Circular Layout
  apply.layout.url = paste(base.url, "apply/layouts/circular", toString(network.suid), sep="/")
  apply.style.url = paste(base.url, "apply/styles/default%20black", toString(network.suid), sep="/")
  
  res <- GET(apply.layout.url)
  res <- GET(apply.style.url)
}

send2cy(cygraph)
## [1] 837

If you want to visualize your network in igraph, obviously it is possible:

plot(g.tca,vertex.label=V(g.tca)$name)

plot of chunk unnamed-chunk-5

This is a static image and there is no interactivity. In contrast, the result you see in the Cytoscape applicaiton window should look like this: