NetworkX

[1]:
import ipycytoscape
import ipywidgets as widgets
import networkx as nx

Undirected graph

[2]:
G = nx.complete_graph(5)
undirected = ipycytoscape.CytoscapeWidget()
undirected.graph.add_graph_from_networkx(G)
display(undirected)

You can also add more nodes

The above graph should update when you run the next cell

[3]:
G2 = nx.Graph()
G2.add_node('separate node 1')
G2.add_node('separate node 2')
G2.add_edge('separate node 1', 'separate node 2')
undirected.graph.add_graph_from_networkx(G2)

Fully directed graphs

add_graph_from_networkx takes an argument directed that if True will ensure all edges given the directed class, which will style them with an arrow.

[4]:
G = nx.complete_graph(5)
directed = ipycytoscape.CytoscapeWidget()
directed.graph.add_graph_from_networkx(G, directed=True)
directed

Mixed graphs

You can also make graphs with both directed and undirected edges by adding ‘directed’ to the ‘classes’ attribute of the edge data

[5]:
from random import random
[6]:
G = nx.complete_graph(5)
for s, t, data in G.edges(data=True):
    if random() > .5:
        G[s][t]['classes'] = 'directed'

mixed = ipycytoscape.CytoscapeWidget()
mixed.graph.add_graph_from_networkx(G)
mixed

Custom networkx Node Objects

The most common choices for Nodes in networkx are numbers or strings as shown above. A node can also be any hashable object (except None) which work as well.

[7]:
class Node:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "Node: " + str(self.name)

n1 = Node("node 1")
n2 = Node("node 2")

G = nx.Graph()

G.add_node(n1)
G.add_node(n2)

G.add_edge(n1, n2)

w = ipycytoscape.CytoscapeWidget()
w.graph.add_graph_from_networkx(G)
w

Custom networkx Node Objects that inherit from ipycytoscape.Node

While custom networkx Node objects work, they do not allow as much control over formatting as you may need. The easiest way to achieve customization with custom Node objects is to subclass ipycytoscape.Node as show below.

[8]:
class CustomNode(ipycytoscape.Node):
    def __init__(self, name, classes=''):
        super().__init__()
        self.data['id'] = name
        self.classes = classes

n1 = CustomNode("node 1", classes='class1')
n2 = CustomNode("node 2", classes='class2')

G = nx.Graph()

G.add_node(n1)
G.add_node(n2)

G.add_edge(n1, n2)

custom_inherited = ipycytoscape.CytoscapeWidget()
custom_inherited.graph.add_graph_from_networkx(G)
custom_inherited.set_style([
                        {
                            'selector': 'node.class1',
                            'css': {
                                'background-color': 'red'
                            }
                        },
                        {
                            'selector': 'node.class2',
                            'css': {
                                'background-color': 'green'
                            }
                        }])
custom_inherited
[ ]: