
Table of Contents
Togglenetworkx python
Networkx Python in JNNC Technologies.
NetworkX
is a Python library used to create, manipulate, and study the structure, dynamics, and functions of complex networks. networkx python. It provides tools to work with both undirected and directed graphs, including functions for analyzing and visualizing networks.
Key Features of NetworkX
:
-
Graph Creation: You can create both simple and complex graphs with nodes, edges, and different types of relationships.
-
Algorithms: Includes a wide variety of graph algorithms like shortest path, clustering, centrality, and more. networkx python
-
Visualization: Provides functionality to plot graphs using Matplotlib.
-
Integration: Supports integration with other libraries like Matplotlib and Pandas.
-
Support for Complex Networks: Handles weighted, bipartite, multigraphs (graphs with multiple edges), and other advanced types of graphs. networkx python
networkx python
Installation
To install NetworkX
, you can use pip:
pip install networkx
Basic Usage Examples
1. Creating a Simple Graph
import networkx as nx
# Create a new graph
G = nx.Graph()
# Add nodes and edges
G.add_node(1)
G.add_node(2)
G.add_edge(1, 2)
# Display graph details
print(“Nodes:”, G.nodes())
print(“Edges:”, G.edges())
2. Adding Multiple Nodes and Edges
# Add multiple nodes
G.add_nodes_from([3, 4, 5])
# Add multiple edgesG.add_edges_from([(2, 3), (4, 5)])
# Display nodes and edgesprint(“Nodes:”, G.nodes())
print(“Edges:”, G.edges())
3. Directed Graph (DiGraph)
# Create a directed graph
DG = nx.DiGraph()
# Add nodes and directed edgesDG.add_edge(1, 2)
DG.add_edge(2, 3)
# Display directed edgesprint(“Directed Edges:”, DG.edges())
4. Graph Visualization
You can visualize the graph using Matplotlib.
import matplotlib.pyplot as plt
# Visualize the graph
nx.draw(G, with_labels=True)
plt.show()
5. Graph Algorithms
-
Shortest Path: Calculate the shortest path between two nodes.
# Shortest path between node 1 and 5
path = nx.shortest_path(G, source=1, target=5)
print("Shortest Path:", path)
-
Degree Centrality: Measures the number of edges connected to a node.
centrality = nx.degree_centrality(G)
print("Degree Centrality:", centrality)
-
Clustering Coefficient: Measures the degree to which nodes tend to cluster together. networkx python.
clustering = nx.clustering(G)
print("Clustering Coefficient:", clustering)
6. Working with Weighted Graphs
# Create a weighted graph
WG = nx.Graph()
WG.add_edge(1, 2, weight=4.2)
WG.add_edge(2, 3, weight=2.5)
# Get edge weightsfor u, v, weight in WG.edges(data=True):
print(f”Edge ({u}, {v}) has weight: {weight[‘weight’]}”)
7. Graph Types Supported
-
Bipartite Graphs: Networks that consist of two disjoint sets of nodes.
-
Multigraphs: Graphs where multiple edges between nodes are allowed.
-
Complete Graphs: Every node is connected to every other node.
Useful NetworkX
Functions
-
nx.connected_components(G)
: Get the connected components of an undirected graph. -
nx.degree_centrality(G)
: Calculate degree centrality for each node. -
nx.betweenness_centrality(G)
: Calculate betweenness centrality. -
nx.clustering(G)
: Calculate the clustering coefficient for each node. -
nx.shortest_path_length(G)
: Calculate the shortest path lengths between nodes.
Conclusion
NetworkX
is a powerful library that allows you to model and analyze real-world networks easily. It can be used in applications ranging from social network analysis, recommendation systems, biological networks, and more.
Let me know if you’d like more examples or need help with a specific graph problem!

Here are more advanced features and examples of NetworkX
for handling complex graph tasks, working with large datasets, and performing network analysis:
1. Working with Large Graphs
-
NetworkX
can handle large graphs, but you need to ensure that you are using the correct techniques to work with such datasets efficiently.
# Create a large random graph
import networkx as nx
import matplotlib.pyplot as plt
# Create a graph with 100 nodes and random edgesG_large = nx.gnp_random_graph(100, 0.05) # 100 nodes, 5% probability of edge creation
# Plot large graph (this might take some time for visualization)nx.draw(G_large, with_labels=False, node_size=30)
plt.show()
2. Graph Isomorphism
-
Graph isomorphism checks whether two graphs are identical in terms of their structure but not necessarily in terms of their labels.
# Check if two graphs are isomorphic
G1 = nx.path_graph(4)
G2 = nx.path_graph(4)
is_isomorphic = nx.is_isomorphic(G1, G2)
print("Graphs are isomorphic:", is_isomorphic)
3. Community Detection with NetworkX
-
Community detection algorithms (like Girvan-Newman, Louvain, etc.) help to identify subgroups within the graph.
# Girvan-Newman community detection
from networkx.algorithms.community import girvan_newman
# Create a graphG = nx.karate_club_graph()
# Apply Girvan-Newman algorithmcommunities = girvan_newman(G)
# Display the first split of the community
first_split = next(communities)
print(“First community split:”, first_split)
4. Random Graph Generation
-
Erdős–Rényi Model (gnp_random_graph): Generates random graphs where each edge is created independently with a given probability.
# Generate a random graph using the Erdős–Rényi model
random_graph = nx.gnp_random_graph(10, 0.3) # 10 nodes, 30% probability for edge creation
# Visualize the random graphnx.draw(random_graph, with_labels=True, node_color=‘skyblue’, font_weight=‘bold’)
plt.show()
-
Small-World Network (Watts-Strogatz Model): This model generates graphs with small-world properties, meaning that most nodes are not neighbors but can be reached from every other by a small number of steps.
# Generate a small-world network (Watts-Strogatz)
small_world_graph = nx.watts_strogatz_graph(30, 4, 0.2) # 30 nodes, 4 neighbors, 20% rewiring probability
# Visualize the small-world graphnx.draw(small_world_graph, with_labels=True, node_color=‘lightgreen’, font_weight=‘bold’)
plt.show()
5. Graph Properties and Measures
-
Degree Distribution: You can analyze the degree (number of neighbors) of each node in the graph.
# Degree of each node
degree_dict = dict(G.degree())
print("Degree of each node:", degree_dict)
# Degree distribution (histogram)degree_sequence = [d for n, d in G.degree()]
plt.hist(degree_sequence, bins=20, color=‘skyblue’, alpha=0.7)
plt.title(“Degree Distribution”)
plt.xlabel(“Degree”)
plt.ylabel(“Frequency”)
plt.show()
6. Centrality Measures
-
Betweenness Centrality: Measures the influence of a node over the spread of information across the network.
# Betweenness centrality
betweenness = nx.betweenness_centrality(G)
print("Betweenness Centrality:", betweenness)
-
Eigenvector Centrality: Measures a node’s influence in the network based on the influence of its neighbors.
# Eigenvector centrality
eigenvector = nx.eigenvector_centrality(G)
print("Eigenvector Centrality:", eigenvector)
7. Shortest Path Algorithms
-
Dijkstra’s Algorithm: Finds the shortest path between nodes in a weighted graph.
# Shortest path using Dijkstra’s algorithm
G_weighted = nx.Graph()
G_weighted.add_edge(1, 2, weight=4)
G_weighted.add_edge(2, 3, weight=1)
G_weighted.add_edge(1, 3, weight=7)
# Get the shortest path from node 1 to node 3shortest_path = nx.dijkstra_path(G_weighted, source=1, target=3, weight=‘weight’)
print(“Shortest path from 1 to 3:”, shortest_path)
8. Clustering and Community Detection
-
Modularity: The Louvain method for community detection focuses on optimizing the modularity of the graph.
# Modularity-based community detection
from networkx.algorithms.community import louvain_communities
# Detect communities using Louvain methodcommunities = louvain_communities(G)
print(“Detected communities:”, communities)
9. Graph Visualization with matplotlib
-
Basic Visualization:
NetworkX
uses Matplotlib to draw basic graphs.
# Basic Graph Visualization
nx.draw(G, with_labels=True, node_size=500, node_color='skyblue', font_weight='bold')
plt.title("Graph Visualization")
plt.show()
-
Advanced Visualization: You can customize node shapes, colors, edge styles, and more for advanced visualizations.
# Advanced Visualization with custom node colors and edge width
nx.draw(G, with_labels=True, node_size=500, node_color='lightgreen', edge_color='blue', width=2, font_size=10)
plt.title("Advanced Graph Visualization")
plt.show()
10. Graph Embeddings
-
Node2Vec: A method to learn low-dimensional representations of nodes.
from node2vec import Node2Vec
# Create a node2vec instance from the graph
node2vec = Node2Vec(G, dimensions=128, walk_length=10, num_walks=100, workers=4)
# Learn the embedding for each node
model = node2vec.fit()
embeddings = model.wv
print(“Node Embeddings:”, embeddings)
11. Graph Analysis for Social Networks
-
Analyzing Social Networks: Use NetworkX for various social network analyses, such as detecting communities, measuring centrality, and more.
# Example: Social network community detection
social_network_graph = nx.erdos_renyi_graph(30, 0.2)
communities = nx.community.label_propagation_communities(social_network_graph)
print("Communities in the social network:", list(communities))
12. Save and Load Graphs
-
You can save and load graphs using standard formats like GML, GraphML, Pickle, or Pajek format.
# Save graph to a file
nx.write_graphml(G, "graph.graphml")
# Load graph from a fileG_loaded = nx.read_graphml(“graph.graphml”)
print(“Loaded Graph:”, G_loaded.nodes())
Conclusion
NetworkX
is a powerful and flexible library that allows you to handle a variety of graph-related tasks, from basic graph creation to complex graph algorithms and visualizations. You can use it to analyze social networks, biological networks, computer networks, and more.
Feel free to ask if you need more help with specific graph algorithms or further examples!