The Wayback Machine - https://web.archive.org/web/20240920171736/https://www.geeksforgeeks.org/networkx-python-software-package-study-complex-networks/
Open In App

NetworkX : Python software package for study of complex networks

Last Updated : 11 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms and draw networks. 

Installation of the package: 

pip install networkx

Creating Nodes

Add one node at a time: 

 G.add_node(1)

Add a list of nodes: 

 G.add_nodes_from([2,3])

Let us create nodes in the graph G. After adding nodes 1, 2, 3, 4, 7, 9 

Creating Nodes

Creating Edges:

Adding one edge at a time: 

G.add_edge(1,2)
G.add_edge(3,1)
G.add_edge(2,4)
G.add_edge(4,1)
G.add_edge(9,1)

Adding a list of edges: 

G.add_edges_from([(1,2),(1,3)])

After adding edges (1,2), (3,1), (2,4), (4,1), (9,1), (1,7), (2,9) 

Creating Edges

Removing Nodes and Edges:

One can demolish the graph using any of these functions: 

Graph.remove_node(), Graph.remove_nodes_from(),
Graph.remove_edge() and Graph.remove_edges_from()

After removing node 3 

Removing Nodes and Edge

After removing edge (1,2) 

After removing edge (1,2)  

Python3




# Python program to create an undirected
# graph and add nodes and edges to a graph
 
# To import package
import networkx
  
# To create an empty undirected graph
G = networkx.Graph()
  
# To add a node
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_node(4)
G.add_node(7)
G.add_node(9)
  
# To add an edge
# Note graph is undirected
# Hence order of nodes in edge doesn't matter
G.add_edge(1,2)
G.add_edge(3,1)
G.add_edge(2,4)
G.add_edge(4,1)
G.add_edge(9,1)
G.add_edge(1,7)
G.add_edge(2,9)
  
# To get all the nodes of a graph
node_list = G.nodes()
print("#1")
print(node_list)
  
# To get all the edges of a graph
edge_list = G.edges()
print("#2")
print(edge_list)
  
# To remove a node of a graph
G.remove_node(3)
node_list = G.nodes()
print("#3")
print(node_list)
  
# To remove an edge of a graph
G.remove_edge(1,2)
edge_list = G.edges()
print("#4")
print(edge_list)
  
# To find number of nodes
n = G.number_of_nodes()
print("#5")
print(n)
  
# To find number of edges
m = G.number_of_edges()
print("#6")
print(m)
  
# To find degree of a node
# d will store degree of node 2
d = G.degree(2)
print("#7")
print(d)
 
# To find all the neighbor of a node
neighbor_list = G.neighbors(2)
print("#8")
print(neighbor_list)
 
#To delete all the nodes and edges
G.clear()


Output: 

#1
[1, 2, 3, 4, 7, 9]
#2
[(1, 9), (1, 2), (1, 3), (1, 4), (1, 7), (2, 4), (2, 9)]
#3
[1, 2, 4, 7, 9]
#4
[(1, 9), (1, 4), (1, 7), (2, 4), (2, 9)]
#5
5
#6
5
#7
2
#8
[4, 9]

In the next post, we’ll be discussing how to create weighted graphs, directed graphs, multi graphs. How to draw graphs. In later posts we’ll see how to use inbuilt functions like Depth first search aka dfs, breadth first search aka BFS, dijkstra’s shortest path algorithm. 



Similar Reads

Python | Visualize graphs generated in NetworkX using Matplotlib
Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package. Step 1 : Import networkx and matplotlib.pyplot in the project
3 min read
Python | Clustering, Connectivity and other Graph properties using Networkx
Triadic Closure for a Graph is the tendency for nodes who has a common neighbour to have an edge between them. In case more edges are added in the Graph, these are the edges that tend to get formed. For example in the following Graph : The edges that are most likely to be formed next are (B, F), (C, D), (F, H), and (D, H) because these pairs share
6 min read
Hyperlink Induced Topic Search (HITS) Algorithm using Networkx Module | Python
Hyperlink Induced Topic Search (HITS) Algorithm is a Link Analysis Algorithm that rates webpages, developed by Jon Kleinberg. This algorithm is used to the web link-structures to discover and rank the webpages relevant for a particular search. HITS uses hubs and authorities to define a recursive relationship between webpages. Before understanding t
4 min read
Network Centrality Measures in a Graph using Networkx | Python
Centrality Measures allows us to pinpoint the most important nodes of a Graph. This essentially helps us to identify : Influential nodes in a Social Network. Nodes that disseminate information to many nodes Hubs in a transportation network Important pages in the Web Nodes that prevent the Network from breaking up Firstly, we need to consider the fa
6 min read
Star Graph using Networkx Python
In this article, we are going to see Star Graph using Networkx Python. A Star graph is a special type of graph in which n-1 vertices have degree 1 and a single vertex have degree n – 1. This looks like that n – 1 vertex is connected to a single central vertex. A star graph with total n – vertex is termed as Sn. Properties of Star Graph: It has n+1
2 min read
Python NetworkX - Tutte Graph
It is a graph with 46 vertices and 69 edges. It is important because it is an exception to Tait's conjecture which states that every 3-regular polyhedron has a Hamiltonian cycle. Properties of Tutte Graph: It is a cubic polyhedral graph which is evident from the diagram above as it is both cubic and polyhedralIt is a Non-Hamiltonian graph.It is a P
2 min read
Barbell Graph Using Python networkx
Prerequisite: networkx There are many kinds of definitions of the barbell graphs. The most commonly used one is an n-barbell graph which is a simple graph obtained by connecting two copies of a complete graph with n nodes. In this article, we are going to see how to use a barbell graph using python. Examples of n-barbell graph: Example 1: If N=3 No
2 min read
Ladder Graph Using Networkx Module in Python
In this article, we are going to see the ladder graph using Python. It is a graph that looks like ladders used commonly with every node attached to two other nodes in a specific manner. We can obtain a ladder graph by joining two-path graphs of n nodes each by each node connected with a corresponding node in another path graph. Representation: Belo
2 min read
Create a Cycle Graph using Networkx in Python
A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified. Properties:Number of nodes in a Cycle Graph(Cn) are equal to N.Number of edges in a Cycle Graph(Cn) are equal to N.Every node is connected to 2 edges hence degree of each node is 2.It is a H
2 min read
Creating a Path Graph Using Networkx in Python
A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function. Properties of Path Graph:The number of nodes in a path graph(Pn) is N.The number of edges in a path grap
2 min read
Lollipop Graph in Python using Networkx module
The lollipop graph consists of 2 components a complete graph called clique and a path graph. More precisely L (m ,n) is a graph with an m-node complete graph and n-node path graph. L(4,2) Lollipop Graph: Here let's see the properties of this graph: So.no Properties of Lollipop Graph: 1 It is a connected graph with two components clique and path gra
3 min read
Complete Graph using Networkx in Python
A complete graph also called a Full Graph it is a graph that has n vertices where the degree of each vertex is n-1. In other words, each vertex is connected with every other vertex. Example: Complete Graph with 6 edges: Properties of Complete Graph: The degree of each vertex is n-1.The total number of edges is n(n-1)/2.All possible edges in a simpl
3 min read
Wheel Graph using Networkx Python
A wheel graph is a type of graph in which if we connect each node in an n-1 node cycle graph to nth node kept at the centre we get a wheel graph. The definition would be more clear after seeing the example below. Wheel Graph with n nodes is represented by Wn . Example: W5: W6: Properties of Wheel Graph: Total number of edges are 2(N-1)It is a plana
2 min read
Ego graph Using Networkx in Python
Prerequisite - Graphs, Networkx Basics Ego network is a special type of network consisting of one central node and all other nodes directly connected to it. The central node is known as ego, while the other surrounding nodes directly connected to it are known as alters. Ego networks are mostly used in analyzing social connections, links, and relati
4 min read
Operations on Graph and Special Graphs using Networkx module | Python
This article shows how to create an undirected Graph. This article continues for other types of Graphs and visualization techniques. The basic Graph operations are as follows: Getting Subgraph from a Graph : Given a Graph, if we are given a subset of its set of nodes, we can create a Subgraph by selecting these nodes and all the edges between them
8 min read
Difference between Graph Isomorphism and Automorphism using Python NetworkX
Graph isomorphism and automorphism are important concepts in graph theory. Graph isomorphism checks the equivalence of two graphs, while graph automorphism deals with the symmetry within a single graph. Using Python NetworkX, we can easily explore and visualize these concepts, making it a valuable tool for studying complex networks. Difference betw
3 min read
Geometry using Complex Numbers <std::complex> in C++ | Set 1
While solving geometric problems, it is time consuming to define the point class for specifying a point on the 2D Plane or the Euclidean Plane. So, this article specifies a faster and clever way to implement the same using complex class from STL in C++. Before implementation, it is essential to understand what are complex numbers and how they can h
5 min read
Saving a Networkx graph in GEXF format and visualize using Gephi
Prerequisites: Networkx NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many type
2 min read
Visualizing the complement of a graph using networkx
Given a graph G complement of the graph is obtained by removing the edges contained in G from the complete graph having the same number of nodes as G. Example: Initial Graph G: The complement of G: Realizing Complement using Python : We will use networkx.complement() function for our task Syntax: networkx.complement() Returns the complement of the
2 min read
Visualizing the composition two of graph using networkx
In this article, we are going to see how to visualize the composition two of the graph using networkx. If we are given two graphs A and B then their composition can be found by performing union operation on node-set and edge-set of A and B. Simply if an edge is contained between any two vertices in any of the initial graphs it will be contained in
3 min read
Resolving the "module 'networkx' has no attribute 'from_pandas_edgelist'" Error
When working with NetworkX, a common library for creating, manipulating, and studying the structure, dynamics, and functions of complex networks, you might encounter the error: "module 'networkx' has no attribute 'from_pandas_edgelist'". This error typically arises due to version discrepancies or incorrect usage of the from_pandas_edgelist function
4 min read
Signed Networks in Social Networks
Prerequisite: Introduction to Social Networks In Social Networks, Network is of 2 types- Unsigned Network and Signed Network. In the unsigned network, there are no signs between any nodes, and in the signed network, there is always a sign between 2 nodes either + or -. The '+' sign indicates friendship between 2 nodes and the '-' sign indicates enm
4 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
How to plot a complex number in Python using Matplotlib ?
In this article we will learn how to plot complex number in Python using Matplotlib. Let's discuss some concepts : Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was int
3 min read
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
Return the Angle of the Complex Argument in Radians in Python using NumPy
In this article, we are going to see how to return the angle of the complex argument in radians in Python Using NumPy. The NumPy library provides the numpy.angle() method to return the angle of the complex argument in radians in python. Let's look at the syntax of the method. Syntax: numpy.angle(z, deg=False) parameters: z: array like object. input
3 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Compute the square root of complex inputs with scimath in Python
In this article, we will cover how to compute the square root of complex inputs with scimath in Python using NumPy. ExampleInput: [-1 -2] Output: [0.+1.j 0.+1.41421356j] Explanation: Square root of complex input.NumPy.emath.sqrt method The np.emath.sqrt() method from the NumPy library calculates the square root of complex inputs. A complex value is
3 min read
Generate a Legendre series with given complex roots in Python
In this article, we will cover how to generate the Legendre series with given complex roots in Python using NumPy. ExampleInput: (4+5j) Output: [9.33333333-40.j 0. +0.j 0.66666667 +0.j] Explanation: An array of legendre series.legendre.legfromroots method In python, the Legendre module provides many functions like legfromroots to perform arithmetic
2 min read
Python NumPy - Return real parts if input is complex with all imaginary parts close to zero
In this article, we will discuss how to return real parts if the input is complex with all imaginary parts close to zero in Python. The numpy np.real_if_close() method is used to return the real parts if the input is a complex number with all imaginary parts close to zero. “Close to zero” is defined as tol * (machine epsilon of the type for a). syn
2 min read
Article Tags :
Practice Tags :