Creating Basic Network Graphs with NetworkX
You'll learn how to build simple network graphs in Python by adding nodes, edges, and attributes to represent relationships between entities.
What Is a Network Graph?
Think of a network graph like a social network diagram: people are dots (nodes), and friendships are lines connecting them (edges). NetworkX is Python's go-to library for creating and analyzing these structures. Whether you're mapping relationships between proteins, analyzing social connections, or visualizing website links, NetworkX provides the foundation.
Building Your First Graph
Start by creating an empty graph and adding elements:
import networkx as nx
# Create an empty graph
G = nx.Graph()
# Add individual nodes
G.add_node("Alice")
G.add_node("Bob")
# Or add multiple nodes at once
G.add_nodes_from(["Charlie", "Diana"])
# Add edges (connections between nodes)
G.add_edge("Alice", "Bob")
G.add_edge("Bob", "Charlie")
G.add_edges_from([("Charlie", "Diana"), ("Diana", "Alice")])
Setting Attributes
Nodes and edges can carry information:
# Add node with attributes
G.add_node("Eve", age=28, city="Boston")
# Add edge with weight
G.add_edge("Alice", "Eve", weight=0.8)
# Access attributes
print(G.nodes["Eve"]) # {'age': 28, 'city': 'Boston'}
print(G.edges["Alice", "Eve"]) # {'weight': 0.8}
Basic Graph Properties
NetworkX provides immediate insights:
print(f"Number of nodes: {G.number_of_nodes()}")
print(f"Number of edges: {G.number_of_edges()}")
print(f"Nodes: {list(G.nodes())}")
print(f"Edges: {list(G.edges())}")
Key Takeaway: NetworkX lets you build network graphs by adding nodes and edges programmatically, attach meaningful attributes to both, and instantly query basic graph properties—forming the foundation for network analysis and visualization.