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
networkx
is used to create and manipulate network graphs.matplotlib.pyplot
is used to visualize the graph.
Creating a Graph Object
G = nx.Graph()
nx.Graph()
initializes an empty undirected graph.
Adding Nodes
G.add_nodes_from(["A", "B", "C", "D", "E"])
- Adds nodes A, B, C, D, and E to the graph.
Adding Edges (Connections between Nodes)
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"), ("C", "E")]
G.add_edges_from(edges)
- Defines edges (connections between nodes).
- Each tuple represents a connection (e.g.,
("A", "B")
means there is an edge between nodes A and B).
Setting Up the Figure
plt.figure(figsize=(8, 6))
- Specifies the figure size for better visualization.
Drawing the Graph
nx.draw(G, with_labels=True, node_color="yellow", node_size=1000,
edge_color="gray", font_size=16, font_weight="bold")
with_labels=True
: Displays node names.node_color="yellow"
: Sets the node color to yellow.node_size=1000
: Increases the node size.edge_color="gray"
: Sets the edge color to gray.font_size=16
: Sets the font size for node labels.font_weight="bold"
: Makes the font bold.
Adding a Title and Showing the Graph
plt.title("Network Graph using Python")
plt.show()
- Adds a title to the plot.
- Displays the network graph.
Enhanced Version with Practical Features
Now, let’s take this one step further! We’ll:
- Add edge weights to represent distances or strengths of connections.
- Use a spring layout for better node distribution.
- Display edge labels to show weights.
- Improve aesthetics for clarity.
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
- Each edge now has a weight (e.g., distance, cost, or strength of connection).
Improved Layout
spring_layout
dynamically positions nodes for better visualization.
Edge Labels
- Displays weights on edges to improve understanding.
Aesthetic Improvements
- Node color changed to
lightblue
for better contrast. - Node size increased for clarity.
- Edge labels added in
red
for better visibility.
How This is Useful:
Social Networks
- Nodes represent people.
- Edges represent friendships or interactions, and their weights indicate strength (e.g., frequency of interaction).
Transportation Systems
- Nodes represent cities.
- Edges represent roads or flight routes.
- Edge weights represent distances or travel times.
Communication Networks
- Nodes represent computers or servers.
- Edges represent connections or bandwidth between systems.
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.