NetworkX Overview
Learn how the NetworkX library is structured and some of its functions and algorithms.
We'll cover the following...
Let’s formally introduce some of NetworkX’s structures and main functionalities.
Graph types
Every graph we create with NetworkX has a type associated with it. There are a total of four graph types we can represent:
Graph: This is the default undirected graph.
DiGraph: This is a default and directed graph.
MultiGraph: This is an undirected multigraph.
MultiDiGraph: This is a directed multigraph.
A MultiGraph is a graph where we can have more than one edge connecting the same two nodes, such as the following: in this case, besides being a MultiGraph, it is also directed, so we can see the edges have a direction.
The creation of each of this kind of graph follows the same syntax with different names:
G = nx.Graph() # Standard GraphG = nx.DiGraph() # DiGraphG = nx.MultiGraph() # MultiGraphG = nx.MultiDiGraph() # MultiDiGraph
Depending on the type of graph we define, some assumptions will automatically be applied. For example, if we say we’re using the nx.Graph()
method to create a simple graph, NetworkX will make the adjacency matrix symmetric. This is because each edge will be represented twice in the matrix, both on the row and column of both nodes it has, which won’t happen with a DiGraph (made using the nx.DiGraph()
method).
We can also convert between graph types. The following two methods can be used to change between directed and undirected graphs:
import networkx as nxG = nx.Graph()G = G.to_directed() # Convert graph to DiGraphG = nx.DiGraph()G = G.to_undirected() # Convert DiGraph to graph
Graph generators
The library also provides a set of graph generators. A graph generator is a function that yields a given graph structure as a result.
The Erdős–Rényi function nx.erdos_renyi_graph()
is an example of this kind of generator. There are several others that generate random models but also more classical structures.
For example, we can use the library to generate a complete graph. A complete graph is a graph where every node is connected to every other node. For example, a complete graph ...