Directed Graphs: Digraph Digraph - Out - Edges Digraph - in - Degree Digraph - Predecessors Digraph - Successors
Directed Graphs: Digraph Digraph - Out - Edges Digraph - in - Degree Digraph - Predecessors Digraph - Successors
>>>
>>> DG = nx.DiGraph()
>>> DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
>>> DG.out_degree(1, weight='weight')
0.5
>>> DG.degree(1, weight='weight')
1.25
>>> list(DG.successors(1))
[2]
>>> list(DG.neighbors(1))
[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
>>>
>>> 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.
>>>
>>> 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'))
{1: 1.25, 2: 1.75, 3: 0.5}
>>> 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)
[1, 2, 3]
Analyzing graphs
The structure of G can be analyzed using various graph-theoretic functions such as:
>>>
>>> G = nx.Graph()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> G.add_node("spam") # adds node "spam"
>>> list(nx.connected_components(G))
[{1, 2, 3}, {'spam'}]
>>> sorted(d for n, d in G.degree())
[0, 1, 1, 2]
>>> nx.clustering(G)
{1: 0, 2: 0, 3: 0, 'spam': 0}
Some functions with large output iterate over (node, value) 2-tuples. These are easily stored
in a dict structure if you desire.
>>>
>>> sp = dict(nx.all_pairs_shortest_path(G))
>>> sp[3]
{3: [3], 1: [3, 1], 2: [3, 1, 2]}
See Algorithms for details on graph algorithms supported.