Using Cytoscape.js in Jupyter Notebook

by Keiichiro Ono


Introduction

If you use Jupyetr Notebook with cyREST, you can script your workflow. And in some cases, you may want to embed the result in the notebook. There are two ways to do it:

  • Embed static PNG image from Cytoscape
  • Convert the result into Cytoscape.js JSON objects, and use it with Cytoscape.js widget

Second option is more appropreate for relatively large networks because users can zoom-in/out to see the detail. In this section, you will learn how to use interactive network visualization widget in py2cytoscape.


In [1]:
# Package to render networks in Cytoscape.js
from py2cytoscape import cytoscapejs as cyjs

# And standard JSON utility
import json


Loading Sample Network

In this example, we use Cytoscape.js JSON files generated by Cytoscape. Input data for this widget should be Cytoscape.js JSON format. You can create those in Cytoscape 3.2.1 OR you can build them programmatically with Python.


In [2]:
# Load network JSON file into this notebook session
yeast_network = json.load(open('sample_data/yeast.json')) # Simple yeast PPI network
kegg_pathway = json.load(open('sample_data/kegg_cancer.cyjs')) # KEGG Pathway

Loading Visual Styles (Optional)

Although this widget includes some preset styles, we recommend to use your custom Visual Style. If you just use Cytoscape.js widget, it is a bit hard to create complex styles manually, but you can interactively create those with Cytoscape 3.


In [3]:
# And Visual Style file in Cytoscape.js format.
vs_collection = json.load(open('sample_data/kegg_style.json'))

# Create map from Title to Style
def add_to_map(key, value, target):
    target[key] = value

styles = {}
map( lambda(x): add_to_map(x["title"], x["style"], styles), vs_collection)

# Display available style names
print(json.dumps(styles.keys(), indent=4))


[
    "Directed", 
    "default", 
    "Nested Network Style", 
    "default black", 
    "Solid", 
    "BioPAX_SIF", 
    "KEGG Style", 
    "Sample1", 
    "BioPAX", 
    "Ripple", 
    "Big Labels", 
    "Universe", 
    "Minimal"
]

Render the result

There are several options for visualization:

  • style - Name of the preset visual style OR Style as JSON object. Default is default
  • layout_algorithm - name of Cytoscape.js layout algorithm. Default is preset
  • background - Background color. Also accepts CSS!

Here is the simplest example: just pass Cytoscape.js object


In [4]:
cyjs.render(yeast_network)



In [5]:
# With custom Style, background color, and layout
cyjs.render(yeast_network, style=styles["default black"], background="black", layout_algorithm="circle")



In [6]:
# With CSS-style Background - with gradient
cyjs.render(yeast_network, style="default2", background="radial-gradient(#FFFFFF 15%, #EEEEEE 105%)", layout_algorithm="breadthfirst")



In [7]:
# And you can reproduce more complex styles created with Cytoscape 3!
cyjs.render(kegg_pathway, style=styles["KEGG Style"])