NetworkX¶

https://github.com/networkx/networkx

Aric A. Hagberg, Daniel A. Schult and Pieter J. Swart, “Exploring network structure, dynamics, and function using NetworkX”, in Proceedings of the 7th Python in Science Conference (SciPy2008), Gäel Varoquaux, Travis Vaught, and Jarrod Millman (Eds), (Pasadena, CA USA), pp. 11–15, Aug 2008 (pdf).

This content is originally downloaded from https://networkx.github.io/documentation/stable/tutorial.html and adapted to be shown as a presentation; moreover, we mix in additional resources such as examples (citing them and the original authors) in the last section.

Creating a graph¶

Create an empty graph with no nodes and no edges.

In [20]:
import networkx as nx
G = nx.Graph()

By definition, a Graph is a collection of nodes (vertices) along with identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can be any hashable object e.g., a text string, an image, an XML object, another Graph, a customized node object, etc.

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

In [2]:
type(G)
Out[2]:
networkx.classes.graph.Graph

Nodes¶

The graph G can be grown in several ways. NetworkX includes many graph generator functions and facilities to read and write graphs in many formats. To get started though we’ll look at simple manipulations. You can add one node at a time,

In [21]:
G.add_node(1)
In [22]:
G.nodes
Out[22]:
NodeView((1,))

add a list of nodes,

In [23]:
G.add_nodes_from([2, 3])
In [24]:
nx.draw(G)
In [7]:
help(G.add_nodes_from)
Help on method add_nodes_from in module networkx.classes.graph:

add_nodes_from(nodes_for_adding, **attr) method of networkx.classes.graph.Graph instance
    Add multiple nodes.
    
    Parameters
    ----------
    nodes_for_adding : iterable container
        A container of nodes (list, dict, set, etc.).
        OR
        A container of (node, attribute dict) tuples.
        Node attributes are updated using the attribute dict.
    attr : keyword arguments, optional (default= no attributes)
        Update attributes for all nodes in nodes.
        Node attributes specified in nodes as a tuple take
        precedence over attributes specified via keyword arguments.
    
    See Also
    --------
    add_node
    
    Examples
    --------
    >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_nodes_from("Hello")
    >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
    >>> G.add_nodes_from(K3)
    >>> sorted(G.nodes(), key=str)
    [0, 1, 2, 'H', 'e', 'l', 'o']
    
    Use keywords to update specific node attributes for every node.
    
    >>> G.add_nodes_from([1, 2], size=10)
    >>> G.add_nodes_from([3, 4], weight=0.4)
    
    Use (node, attrdict) tuples to update attributes for specific nodes.
    
    >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
    >>> G.nodes[1]["size"]
    11
    >>> H = nx.Graph()
    >>> H.add_nodes_from(G.nodes(data=True))
    >>> H.nodes[1]["size"]
    11

or add any iterable container of nodes. You can also add nodes along with node attributes if your container yields 2-tuples (node, node_attribute_dict). Node attributes are discussed further below.

In [25]:
H = nx.path_graph(10)
In [26]:
nx.draw(H)
In [11]:
type(H)
Out[11]:
networkx.classes.graph.Graph
In [12]:
G.add_nodes_from(H)

Note that G now contains the nodes of H as nodes of G. In contrast, you could use the graph H as a node in G.

In [9]:
G.add_node(H)

The graph G now contains H as a node. This flexibility is very powerful as it allows graphs of graphs, graphs of files, graphs of functions and much more. It is worth thinking about how to structure your application so that the nodes are useful entities. Of course you can always use a unique identifier in G and have a separate dictionary keyed by identifier to the node information if you prefer.

Edges¶

G can also be grown by adding one edge at a time,

In [13]:
G.add_edge(1, 2)
e = (2, 3)
G.add_edge(*e)  # unpack edge tuple*

by adding a list of edges,

In [8]:
G.add_edges_from([(1, 2), (1, 3)])

or by adding any ebunch of edges. An ebunch is any iterable container of edge-tuples. An edge-tuple can be a 2-tuple of nodes or a 3-tuple with 2 nodes followed by an edge attribute dictionary, e.g., (2, 3, {'weight': 3.1415}). Edge attributes are discussed further below

In [14]:
G.add_edges_from(H.edges)
In [15]:
G.edges
Out[15]:
EdgeView([(1, 2), (1, 0), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)])

There are no complaints when adding existing nodes or edges. For example, after removing all nodes and edges,

In [16]:
G.clear()
In [17]:
len(G)
Out[17]:
0

we add new nodes/edges and NetworkX quietly ignores any that are already present.

In [11]:
G.add_edges_from([(1, 2), (1, 3)])
G.add_node(1)
G.add_edge(1, 2)
G.add_node("spam")        # adds node "spam"
G.add_nodes_from("spam")  # adds 4 nodes: 's', 'p', 'a', 'm'
G.add_edge(3, 'm')

At this stage the graph G consists of 8 nodes and 3 edges, as can be seen by:

In [12]:
G.number_of_nodes()
Out[12]:
8
In [13]:
G.number_of_edges()
Out[13]:
3

We can examine the nodes and edges. Four basic graph properties facilitate reporting: G.nodes, G.edges, G.adj and G.degree. These are set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. They offer a continually updated read-only view into the graph structure. They are also dict-like in that you can look up node and edge data attributes via the views and iterate with data attributes using methods .items(), .data('span'). If you want a specific container type instead of a view, you can specify one. Here we use lists, though sets, dicts, tuples and other containers may be better in other contexts.

In [14]:
list(G.nodes)
Out[14]:
[1, 2, 3, 'spam', 's', 'p', 'a', 'm']
In [15]:
list(G.edges)
Out[15]:
[(1, 2), (1, 3), (3, 'm')]
In [16]:
list(G.adj[1])  # or list(G.neighbors(1))
Out[16]:
[2, 3]
In [17]:
G.degree[1]  # the number of edges incident to 1
Out[17]:
2

One can specify to report the edges and degree from a subset of all nodes using an nbunch. An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph.

In [18]:
G.edges([2, 'm']), G.degree([2, 3])
Out[18]:
(EdgeDataView([(2, 1), ('m', 3)]), DegreeView({2: 1, 3: 2}))

One can remove nodes and edges from the graph in a similar fashion to adding. Use methods Graph.remove_node(), Graph.remove_nodes_from(), Graph.remove_edge() and Graph.remove_edges_from(), e.g.

In [19]:
G.remove_node(2)
G.remove_nodes_from("spam")
list(G.nodes)
Out[19]:
[1, 3, 'spam']
In [20]:
G.remove_edge(1, 3)

When creating a graph structure by instantiating one of the graph classes you can specify data in several formats.

In [21]:
G.add_edge(1, 2)
H = nx.DiGraph(G)   # create a DiGraph using the connections from G
list(H.edges())
Out[21]:
[(1, 2), (2, 1)]
In [22]:
edgelist = [(0, 1), (1, 2), (2, 3)]
H = nx.Graph(edgelist)

What to use as nodes and edges¶

You might notice that nodes and edges are not specified as NetworkX objects. This leaves you free to use meaningful items as nodes and edges. The most common choices are numbers or strings, but a node can be any hashable object (except None), and an edge can be associated with any object x using G.add_edge(n1, n2, object=x).

As an example, n1 and n2 could be protein objects from the RCSB Protein Data Bank, and x could refer to an XML record of publications detailing experimental observations of their interaction.

We have found this power quite useful, but its abuse can lead to unexpected surprises unless one is familiar with Python. If in doubt, consider using convert_node_labels_to_integers() to obtain a more traditional graph with integer labels.

Accessing edges and neighbors¶

In addition to the views Graph.edges(), and Graph.adj(), access to edges and neighbors is possible using subscript notation.

In [23]:
G[1]  # same as G.adj[1]
Out[23]:
AtlasView({2: {}})
In [24]:
G[1][2], G.edges[1, 2]
Out[24]:
({}, {})

You can get/set the attributes of an edge using subscript notation if the edge already exists.

In [25]:
G.add_edge(1, 3)
G[1][3]['color'] = "blue"
G.edges[1, 2]['color'] = "red"

Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items(). Note that for undirected graphs, adjacency iteration sees each edge twice.

In [26]:
FG = nx.Graph()
FG.add_weighted_edges_from(
    [(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
for n, nbrs in FG.adj.items():
   for nbr, eattr in nbrs.items():
       wt = eattr['weight']
       if wt < 0.5: print('(%d, %d, %.3f)' % (n, nbr, wt))
(1, 2, 0.125)
(2, 1, 0.125)
(3, 4, 0.375)
(4, 3, 0.375)

Convenient access to all edges is achieved with the edges property.

In [27]:
for (u, v, wt) in FG.edges.data('weight'):
    if wt < 0.5: print('(%d, %d, %.3f)' % (u, v, wt))
(1, 2, 0.125)
(3, 4, 0.375)

Adding attributes to graphs, nodes, and edges¶

Attributes such as weights, labels, colors, or whatever Python object you like, can be attached to graphs, nodes, or edges.

Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but attributes can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named G.graph, G.nodes, and G.edges for a graph G.

Graph attributes¶

Assign graph attributes when creating a new graph

In [18]:
G = nx.Graph(day="Friday")
G.graph
Out[18]:
{'day': 'Friday'}
In [19]:
type(_)
Out[19]:
dict

Or you can modify attributes later

In [29]:
G.graph['day'] = "Monday"
G.graph
Out[29]:
{'day': 'Monday'}

Node attributes¶

Add node attributes using add_node(), add_nodes_from(), or G.nodes

In [30]:
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
G.nodes[1]
Out[30]:
{'time': '5pm'}
In [31]:
G.nodes[1]['room'] = 714
G.nodes.data()
Out[31]:
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})

Note that adding a node to G.nodes does not add it to the graph, use G.add_node() to add new nodes. Similarly for edges.

Edge Attributes¶

Add/change edge attributes using add_edge(), add_edges_from(), or subscript notation.

In [32]:
G.add_edge(1, 2, weight=4.7 )
G.add_edges_from([(3, 4), (4, 5)], color='red')
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2

The special attribute weight should be numeric as it is used by algorithms requiring weighted edges.

Directed graphs

The DiGraph class provides additional properties specific to directed edges, e.g., DiGraph.out_edges(), DiGraph.in_degree(), DiGraph.predecessors(), DiGraph.successors() etc. To allow algorithms to work with both classes easily, the directed versions of neighbors() is equivalent to successors() while degree reports the sum of in_degree and out_degree even though that may feel inconsistent at times.

In [33]:
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
DG.out_degree(1, weight='weight'), DG.degree(1, weight='weight')
Out[33]:
(0.5, 1.25)
In [34]:
list(DG.successors(1)), list(DG.neighbors(1))
Out[34]:
([2], [2])

Some algorithms work only for directed graphs and others are not well defined for directed graphs. Indeed the tendency to lump directed and undirected graphs together is dangerous. If you want to treat a directed graph as undirected for some measurement you should probably convert it using Graph.to_undirected() or with

In [35]:
H = nx.Graph(G)  # convert G to undirected graph

Multigraphs¶

NetworkX provides classes for graphs which allow multiple edges between any pair of nodes. The MultiGraph and MultiDiGraph classes allow you to add the same edge twice, possibly with different edge data. This can be powerful for some applications, but many algorithms are not well defined on such graphs. Where results are well defined, e.g., MultiGraph.degree() we provide the function. Otherwise you should convert to a standard graph in a way that makes the measurement well defined.

In [36]:
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
dict(MG.degree(weight='weight'))
Out[36]:
{1: 1.25, 2: 1.75, 3: 0.5}
In [37]:
GG = nx.Graph()
for n, nbrs in MG.adjacency():
   for nbr, edict in nbrs.items():
       minvalue = min([d['weight'] for d in edict.values()])
       GG.add_edge(n, nbr, weight = minvalue)

nx.shortest_path(GG, 1, 3)
Out[37]:
[1, 2, 3]

Graph generators and graph operations¶

In addition to constructing graphs node-by-node or edge-by-edge, they can also be generated by

  1. Applying classic graph operations, such as:

    subgraph(G, nbunch)      - induced subgraph view of G on nodes in nbunch
    union(G1,G2)             - graph union
    disjoint_union(G1,G2)    - graph union assuming all nodes are different
    cartesian_product(G1,G2) - return Cartesian product graph
    compose(G1,G2)           - combine graphs identifying nodes common to both
    complement(G)            - graph complement
    create_empty_copy(G)     - return an empty copy of the same graph class
    to_undirected(G) - return an undirected representation of G
    to_directed(G)   - return a directed representation of G
  2. Using a call to one of the classic small graphs, e.g.,

In [3]:
petersen = nx.petersen_graph()
nx.draw(petersen)
In [4]:
tutte = nx.tutte_graph()
nx.draw(tutte)
In [5]:
maze = nx.sedgewick_maze_graph()
nx.draw(maze)
In [6]:
tet = nx.tetrahedral_graph()
nx.draw(tet)
In [7]:
K_5 = nx.complete_graph(5)
nx.draw(K_5)
In [8]:
K_3_5 = nx.complete_bipartite_graph(3, 5)
nx.draw(K_3_5)
In [9]:
barbell = nx.barbell_graph(10, 10)
nx.draw(barbell)
In [10]:
lollipop = nx.lollipop_graph(10, 20)
nx.draw(lollipop)
In [11]:
er = nx.erdos_renyi_graph(100, 0.15)
nx.draw(er)
In [12]:
ws = nx.watts_strogatz_graph(30, 3, 0.1)
nx.draw(ws)