NetworkX graph and Network Visualisation :¶
Introduction:¶
NetworkX is a Python Library which is used for working on the Graphs. It helps to create the graphs amd also helps to analyze of it. NetworkX explains only a very basic way using syntax like nx.draw() to show the graphs using matplot.NetworkX is simple but not very efficient. These are the key features of NetworkX :
1.Graph Creation: Networkx helps us to built the graph by using the given data
2.Graph Representation: It helps us to to understand the way of connections in the given data.
3.Graph Algorithms: It helps us to conduct the tasks on the graph and helps to solve the problems
4.Graph Visualization:It helps us to Visualisation and helps to analyze the data
These are the main features of NetworkX
Installing the NetworkX:¶
The way of installing the NetworkX in the windows:
For installing the NetworkX in the windows.Open Command prompt and run code "pip install networkx". For verifying it open pyton and execute code NetworkX. If codes run without problem then we can conform that NetworkX is sucessfully installed in the windows.
For upgrading the NetworkX use command of "pip install --upgrade networkx"
Key features and Explanation¶
The features used to create the graphs:
1.For creating the Undirected Graphs by using the syntax nx.Graph
2.For creating the directed Graphs by using the syntax nx.DiGraph
3.For creating the Multigraphs Graphs by using the syntax nx.MultiGraph
The differences between undirected and directed graphs is :
Undirected Graphs:
These are the graphs that has no directions on edges. You can traverse the edge in either direction.
- Simple pair node
- Connection is symmetric
- Each vertex has a degree as number of edges connected to it. Since the edges are bidirectional, the degree count is total number of edges connected to a node
- These are often used to model relationships where direction doesn’t matter, such as in social networks (friendships), computer networks (connected devices), or undirected physical connections like roads or railways.
Directed Graphs:
These are the graphs that has specific direction, it means that each edge points from one node to another in the given direction only.
- Ordered pair node
- Connection is assymetric
- Each vertex has two degree: Indegree( the number of edges into the vertex), Outdegree( the number of edges out the vertex)
- These are used for modeling systems where direction matters, such as web pages (where hyperlinks go from one page to another), traffic flow (one-way streets), or dependencies in task scheduling.
MultiGraph:
A MultiGraph is a specialized type of graph used in graph theory and computer science where multiple edges (or connections) can exist between any two nodes (vertices). This contrasts with the typical graph structure, where there is at most one edge between two vertices.
For other types of graphs
Graph visualisation¶
For this purpose there ar many libraries can be used for this purpose like Matplot integration,layout algorithms.
The built-in nx.draw() function can draw a graph and customize node sizes, colors, edge widths, etc.
It also Supports various formats to import/export graphs, including GraphML GML Pajek Adjacency List/Matrix
Network Metrics and Statistics¶
It helps for various types
Degree Distribution: Calculate the degree (number of connections) for nodes in the graph
Path Lengths: Functions to compute the average shortest path length, diameter, etc., of the graph
Clustering Coefficient: Measures the tendency of nodes to cluster together in the graph
Assortativity: Measures the correlation of node degrees in the graph.
These are the key features of NetworkX
Saving the Networkx graph in gexf format¶
Codes regarding NetworkX¶
#1. Simple Graph Example
import networkx as nx
import matplotlib.pyplot as plt
# Create a graph object
G = nx.Graph()
# Add nodes
G.add_nodes_from([1, 2, 3, 4])
# Add edges between nodes
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])
# Draw the graph
nx.draw(G, with_labels=True, node_color='lightblue', font_weight='bold', node_size=700)
plt.title("Simple Graph")
plt.show()
#2. Directed Graph Example
#This example shows how to create a directed graph (with arrows pointing in a specific direction).
import networkx as nx
import matplotlib.pyplot as plt
# Create a directed graph
G = nx.DiGraph()
# Add nodes
G.add_nodes_from([1, 2, 3, 4])
# Add directed edges (edges with direction)
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])
# Draw the directed graph
nx.draw(G, with_labels=True, node_color='lightgreen', font_weight='bold', node_size=700, arrows=True)
plt.title("Directed Graph")
plt.show()
#3. Weighted Graph Example
#In this example, we add weights to the edges of the graph.
import networkx as nx
import matplotlib.pyplot as plt
# Create a weighted graph
G = nx.Graph()
# Add nodes
G.add_nodes_from([1, 2, 3, 4])
# Add weighted edges
G.add_edge(1, 2, weight=4)
G.add_edge(2, 3, weight=2)
G.add_edge(3, 4, weight=5)
G.add_edge(4, 1, weight=3)
# Draw the graph with edge weights
pos = nx.spring_layout(G) # positions for nodes
nx.draw(G, pos, with_labels=True, node_color='lightcoral', node_size=700, font_weight='bold')
# Draw edge labels (weights)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title("Weighted Graph")
plt.show()
#4. Bipartite Graph Example
#This example shows how to create a bipartite graph, where nodes are divided into two sets.
import networkx as nx
import matplotlib.pyplot as plt
# Create a bipartite graph
B = nx.Graph()
# Add nodes with a bipartite attribute
B.add_nodes_from([1, 2, 3], bipartite=0) # Set 0
B.add_nodes_from([4, 5, 6], bipartite=1) # Set 1
# Add edges between the two sets
B.add_edges_from([(1, 4), (2, 5), (3, 6)])
# Draw the bipartite graph
pos = nx.bipartite_layout(B, nodes=[1, 2, 3]) # Position nodes of set 0 on top
nx.draw(B, pos, with_labels=True, node_color='lightblue', node_size=700, font_weight='bold')
plt.title("Bipartite Graph")
plt.show()
#5. Random Graph Example
#Here’s an example where we generate a random graph using the erdos_renyi_graph method.
import networkx as nx
import matplotlib.pyplot as plt
# Generate a random graph (Erdős-Rényi model)
G = nx.erdos_renyi_graph(n=10, p=0.3) # n=10 nodes, p=0.3 probability of edge creation
# Draw the random graph
nx.draw(G, with_labels=True, node_color='lightgreen', font_weight='bold', node_size=700)
plt.title("Random Graph")
plt.show()
The real life examples for the usage of NetworkX¶
These are the usages of NetworkX in real life:
1.In social media platforms:
It can be used as following networks of users can be represented as graphs, where users are nodes, and their interactions (like friendships or followings) are edges. One of the most common tasks is to detect communities
2.Transportation and Logistics
In transportation networks, you can use graphs to find the shortest or most efficient routes between two points.
3.Biology
In biology, networks of genes or proteins can be represented as graphs, where nodes represent genes and edges represent interactions between them.
4.Network Traffic
In computer networks, routers and switches can be represented as nodes, and network links can be represented as edges.
5.Supply Chain and Inventory Management
In supply chains, inventory systems can be modeled as graphs where products and warehouses are nodes, and edges represent the flow of goods.
Syntaxes regarding NetworkX¶
1.Undirected Graph:nx.Graph()
2.Directed Graph:nx.DiGraph()
3.MultiGraph:nx.MultiGraph()
4.MultiDiGraph:nx.MultiDiGraph()
5.Add nodes:G.add_nodes_from([2, 3, 4])
6.Adding edges:G.add_edges_from([(1, 2), (2, 3)])italicized text
7.Shortest path length:nx.shortest_path_length
8.Graph Algorithms:components = list(nx.connected_components(G)) ,scc = list(nx.strongly_connected_components(G)) ,clustering = nx.clustering(G, 1)
9.Pathfinding Algorithms:path = nx.dijkstra_path(G, source=1, target=4, weight='weight') ,path = nx.astar_path(G, source=1, target=4, heuristic=None, weight='weight')
- Subgraphs:subgraph = G.subgraph([1, 2, 3])
11.Graph Metrics:centrality = nx.betweenness_centrality(G) ,centrality = nx.closeness_centrality(G) ,pagerank = nx.pagerank(G)
Scrapy Project¶
A Scrapy project is a framework for building web crawlers and scrapers in Python. It allows you to extract and process data from websites in an automated way. Scrapy is highly efficient and is widely used for web scraping, data mining, and extracting information from websites for various purposes, such as research, business intelligence, and machine learning datasets.
Conclusion¶
NetworkX is a powerful and versatile library for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. With its simple and intuitive API, it allows users to model various types of networks, including graphs, trees, and directed acyclic graphs (DAGs), and perform tasks like graph traversal, pathfinding, clustering, and visualization. Additionally, it supports the analysis of both small and large-scale networks, integrating seamlessly with other Python libraries for scientific computing like NumPy and SciPy
NetworkX provides the tools needed to explore and understand networks effectively
Refrences and further information:¶
These are the further websites for more information of NetworkX