Drawing a network graph with networkX and Matplotlib

NetworkX is a Python library for creating, manipulating, and studying complex networks. Combined with Matplotlib, it provides powerful visualization capabilities for drawing network graphs with customizable node and edge properties.

Basic Network Graph Creation

To create a simple network graph, we first need to prepare our data and then use NetworkX to build the graph structure ?

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# Set figure size for better visualization
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create a DataFrame with edge connections
df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A', 'D'], 
    'to': ['D', 'A', 'E', 'C', 'E']
})

print("Edge connections:")
print(df)
Edge connections:
  from to
0    A  D
1    B  A
2    C  E
3    A  C
4    D  E

Drawing the Network Graph

Now we can create a graph from the edge list and visualize it with customized node properties ?

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create DataFrame with connections
df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A', 'D'], 
    'to': ['D', 'A', 'E', 'C', 'E']
})

# Create graph from edge list
G = nx.from_pandas_edgelist(df, 'from', 'to')

# Draw the graph with customized properties
nx.draw(G, 
        with_labels=True,      # Show node labels
        node_size=1000,        # Node size
        node_color='lightblue', # Node color
        font_size=16,          # Label font size
        font_weight='bold',    # Label font weight
        edge_color='gray',     # Edge color
        linewidths=2,          # Node border width
        alpha=0.8)             # Transparency

plt.title("Network Graph Visualization", fontsize=18, fontweight='bold')
plt.show()

Advanced Graph Layouts

NetworkX provides different layout algorithms to position nodes. Here's an example using spring layout with custom positioning ?

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [12, 8]

# Create a more complex network
df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A', 'D', 'E', 'F', 'B'], 
    'to': ['D', 'A', 'E', 'C', 'E', 'F', 'A', 'F']
})

G = nx.from_pandas_edgelist(df, 'from', 'to')

# Use spring layout for better positioning
pos = nx.spring_layout(G, k=2, iterations=50)

# Create subplots for comparison
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

# Default layout
ax1.set_title("Default Layout")
nx.draw(G, ax=ax1, with_labels=True, node_size=800, 
        node_color='lightcoral', font_size=12, font_weight='bold')

# Spring layout
ax2.set_title("Spring Layout")
nx.draw(G, pos=pos, ax=ax2, with_labels=True, node_size=800,
        node_color='lightgreen', font_size=12, font_weight='bold')

plt.tight_layout()
plt.show()

Graph Properties

We can analyze basic properties of our network graph ?

import pandas as pd
import networkx as nx

# Create the graph
df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A', 'D'], 
    'to': ['D', 'A', 'E', 'C', 'E']
})

G = nx.from_pandas_edgelist(df, 'from', 'to')

# Display graph properties
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())}")
print(f"Node degrees: {dict(G.degree())}")
Number of nodes: 5
Number of edges: 5
Nodes: ['A', 'D', 'B', 'C', 'E']
Edges: [('A', 'D'), ('A', 'C'), ('D', 'E'), ('B', 'A'), ('C', 'E')]
Node degrees: {'A': 3, 'D': 2, 'B': 1, 'C': 2, 'E': 2}

Conclusion

NetworkX with Matplotlib provides a powerful combination for network visualization. Use nx.from_pandas_edgelist() to create graphs from data, customize appearance with nx.draw() parameters, and experiment with different layouts like spring_layout() for optimal visualization.

Updated on: 2026-03-25T21:20:09+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements