Draw molecular network on Jupyter notebook with rdkit and cytoscape.js-2 #RDKit #cytoscape

Yesterday, I posted about cyjupyter. And got comment how to render the compound name on each node.

I think it is possible to use context attribute in style settings.

Let’s try. Code is almost same as yesterday

import networkx as nx
from networkx.readwrite import cytoscape_data
from rdkit import Chem
from rdkit.Chem import RDConfig
from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
from rdkit.Chem import rdChemReactions
from rdkit.Chem.Draw import rdMolDraw2D
import cyjupyter
from cyjupyter import Cytoscape
import os
from urllib import parse
mmp_path = os.path.join(RDConfig.RDContribDir, "mmpa/data/sample_mmps_default.csv")
lines = []
with open(mmp_path, 'r') as f:
    for line in f:
nodes = set()
for line in lines:
nodes = list(nodes)
print(str(len(nodes))+' mols')
def smi2svg(smi):
    mol = Chem.MolFromSmiles(smi)
    drawer = rdMolDraw2D.MolDraw2DSVG(400, 200)
    svg = drawer.GetDrawingText().replace("svg:", "")
    return svg

def smi2image(smi):
    svg_string = smi2svg(smi)
    impath = 'data:image/svg+xml;charset=utf-8,' + parse.quote(svg_string, safe="")
    return impath

Networkx is easy to make network with many attributes. I set smiles as name attribute.

g = nx.Graph()
for node in nodes:
    g.add_node(node, img=smi2image(node), name=node)
for line in lines:
    g.add_edge(line[0], line[1])
  {'style': [{'css': {
      'background-color': 'blue',
      'shape' : 'rectangle',
      'border-color': 'rgb(0,0,0)',
      'border-opacity': 1.0,
      'border-width': 0.0,
      'color': '#4579e8',
      "font-size": "60px",
    'selector': 'node'},
            {'css': {
                'width': 20.0,
            'selector': 'edge'}

OK let’s draw network!

cyobj=Cytoscape(data=cy_g, visual_style=stobj[0]['style'], layout_name='cose')

Now, SMILES strings can be shown as node name.



Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: