DEV Community

Abhi-Kmr2046
Abhi-Kmr2046

Posted on

How to Work with NetworkX

NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It provides software for complex networks, data structures for graphs, digraphs, and multigraphs, many standard graph algorithms, network structure and analysis measures, generators for classic graphs, random graphs, and synthetic networks.

To install networkX library run the command pip install networkx.

Graph Creation

import networkx as nx
G = nx.Graph()
Enter fullscreen mode Exit fullscreen mode

This creates a empty graph. A graph in networkX is collection of nodes (vertices) along with identified pairs of nodes. A node can be any hashable object e.g., string, image, or another Graph etc.

Nodes

To add nodes we can use one of the following functions:

  • G.add_node(1) creates a single node

  • G.add_nodes_from([2, 3]) creates nodes 2, 3.

Edges

Similar to edges we also have two function to add edges to the graph.

  • G.add_edge(1,2) creates a edge between nodes 1 and 2.

  • G.add_nodes_from([(1, 2), (1, 3)]) creates edges between 1,2 and 1,3.

Visualize Graphs

NetworkX supports basic graph drawing using the matplotlib library.

import networkx as nx
import matplotlib.pyplot as plt
G = nx.complete_graph(6)
nx.draw(G)
plt.show()
Enter fullscreen mode Exit fullscreen mode

This will first create a complete graph with 6 nodes.
Image description

plt.show() is important to show the graph image on screen.

Top comments (0)