import ipycytoscape
import ipywidgets as widgets
import networkx as nx
G = nx.complete_graph(5)
undirected = ipycytoscape.CytoscapeWidget()
undirected.graph.add_graph_from_networkx(G)
display(undirected)
CytoscapeWidget(cytoscape_layout={'name': 'cola'}, cytoscape_style=[{'selector': 'node', 'css': {'background-c…
The above graph should update when you run the next cell
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)
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.
G = nx.complete_graph(5)
directed = ipycytoscape.CytoscapeWidget()
directed.graph.add_graph_from_networkx(G, directed=True)
directed
CytoscapeWidget(cytoscape_layout={'name': 'cola'}, cytoscape_style=[{'selector': 'node', 'css': {'background-c…
You can also make graphs with both directed and undirected edges by adding 'directed' to the 'classes' attribute of the edge data
from random import random
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
CytoscapeWidget(cytoscape_layout={'name': 'cola'}, cytoscape_style=[{'selector': 'node', 'css': {'background-c…
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.
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
CytoscapeWidget(cytoscape_layout={'name': 'cola'}, cytoscape_style=[{'selector': 'node', 'css': {'background-c…
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.
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
CytoscapeWidget(cytoscape_layout={'name': 'cola'}, cytoscape_style=[{'selector': 'node.class1', 'css': {'backg…