Site icon FSIBLOG

How to Create a Network Graph in Python

How to Create a Network Graph in Python

I love working with Python, especially when it comes to visualizing data in an interactive and intuitive way. Today, I’ll walk you through how to create and enhance a network graph using Python’s networkx and matplotlib libraries. This guide will help you understand how to represent relationships between different entities effectively.

Explanation of the Code

This Python script uses networkx and matplotlib to create and visualize a network graph, which consists of nodes (points) and edges (connections between points).

Importing Libraries

import networkx as nx
import matplotlib.pyplot as plt

Creating a Graph Object

G = nx.Graph()

Adding Nodes

G.add_nodes_from(["A", "B", "C", "D", "E"])

Adding Edges (Connections between Nodes)

edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"), ("C", "E")]
G.add_edges_from(edges)

Setting Up the Figure

plt.figure(figsize=(8, 6))

Drawing the Graph

nx.draw(G, with_labels=True, node_color="yellow", node_size=1000,
        edge_color="gray", font_size=16, font_weight="bold")

Adding a Title and Showing the Graph

plt.title("Network Graph using Python")
plt.show()

Enhanced Version with Practical Features

Now, let’s take this one step further! We’ll:

Enhanced Code with Practical Functionality

import networkx as nx
import matplotlib.pyplot as plt

# Initialize a graph
G = nx.Graph()

# Define nodes
nodes = ["A", "B", "C", "D", "E"]
G.add_nodes_from(nodes)

# Define weighted edges (connections with distances/weights)
edges = [("A", "B", 4), ("A", "C", 2), ("B", "C", 5), ("B", "D", 10), ("C", "E", 3)]
G.add_weighted_edges_from(edges)  # Adds edges with weights

# Set figure size
plt.figure(figsize=(8, 6))

# Position nodes using the spring layout for a visually appealing arrangement
pos = nx.spring_layout(G)

# Draw nodes and edges
nx.draw(G, pos, with_labels=True, node_color="lightblue", node_size=1500, edge_color="gray", font_size=14, font_weight="bold")

# Add edge labels (weights)
edge_labels = {(u, v): d for u, v, d in edges}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=12, font_color="red")

# Add a title
plt.title("Enhanced Network Graph with Weighted Edges")

# Show the graph
plt.show()

New Functionalities Added:

Weighted Edges

Improved Layout

Edge Labels

Aesthetic Improvements

How This is Useful:

Social Networks

Transportation Systems

Communication Networks

Conclusion

By following this guide, you’ve learned how to create and visualize a network graph in Python using networkx and matplotlib. You’ve also seen how to enhance the graph with weighted edges, labels, and a better layout for practical use cases.

Exit mobile version