Welcome to the NetworkX getting started guide. The is the perfect place for graph enthusiasts who are starting their journey through the NetworkX Python package. Follow the next few steps to get a basic understanding of the most important concepts in NetworkX.
For the getting started guide you need to have Python and NetworkX installed locally.
If that's not the case for you, check out our Installation guide.
Create a new text file with the name
networkx.py and the following code:
import networkx as nx G = nx.Graph()
This code will create an empty NetworkX graph without any nodes or edges.
Graph object is a collection of nodes (vertices) and edges (links, relationships).
Nodes can be any hashable object like a string, an image, an XML object, another Graph, etc. You can find the complete list here.
If you want to add a node to your newly created graph, add the following line to your code:
You can also add multiple nodes at once:
Just like nodes, edges can be added one at a time:
Multiple edges can be added at once:
G.add_edges_from([(1, 2), (1, 3)])
To check out the number of nodes or edges, use the
number_of_edges() methods respectively:
To list out the actual edges and nodes in the graph:
The following methods are used to remove nodes and edges:
G.remove_node(1)G.remove_nodes_from([1, 2, 3])