DEV Community

Abhi-Kmr2046
Abhi-Kmr2046

Posted on

1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay