A Directed Graph is a graph that is made up of a set of vertices connected by edges, where the edges have a direction associated with them. It differs from an ordinary or undirected graph, in that the latter is defined in terms of unordered pairs of vertices, which are usually called edges, arcs, or lines.
In NetworkX, we can make directed graphs using the DiGraph class.
The DiGraph class provides additional methods and 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.
In the below program we will create a directed graph with weighted edges. Then, we will print different properties to understand how the DiGraph() works.
import networkx as nx
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
print(DG.out_degree(1, weight='weight'))
print(DG.degree(1, weight='weight'))
print(list(DG.successors(1)))
print(list(DG.neighbors(1)))
The output looks like this
0.5 1.25 [2] [2]
The graph we created looks like this
Some algorithms work only for directed graphs and others are not well defined for directed graphs. So, we might need sometimes to convert a directed graph to undirected for some calculations. We can do this using
G = nx.Graph(DG)
or
G = DG.to_undirected()
The output is the same which is the below graph.
Comments