How to show node name in Matplotlib graphs using networkx?

To show node names in graphs using NetworkX, you need to set the with_labels parameter to True in the draw() method. This displays the node identifiers directly on the graph.

Basic Example with Node Labels

Here's how to create a simple directed graph with visible node names ?

import matplotlib.pyplot as plt
import networkx as nx

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create a directed graph
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3), (1, 4), (3, 4)])

# Draw the graph with node labels
nx.draw(G, with_labels=True, node_color='lightblue', 
        node_size=500, font_size=16, font_weight='bold')

plt.show()

Custom Node Labels

You can also use custom labels instead of the default node identifiers ?

import matplotlib.pyplot as plt
import networkx as nx

plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True

# Create graph with string nodes
G = nx.Graph()
nodes = ['Alice', 'Bob', 'Charlie', 'David']
G.add_nodes_from(nodes)
G.add_edges_from([('Alice', 'Bob'), ('Bob', 'Charlie'), 
                  ('Alice', 'David'), ('Charlie', 'David')])

# Draw with custom positioning
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightcoral', 
        node_size=800, font_size=12, font_weight='bold')

plt.title("Social Network Graph")
plt.show()

Using draw_networkx_labels() for More Control

For advanced label customization, use draw_networkx_labels() separately ?

import matplotlib.pyplot as plt
import networkx as nx

plt.rcParams["figure.figsize"] = [8.00, 6.00]

# Create graph
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])

# Custom labels
labels = {1: 'Start', 2: 'Process', 3: 'Decision', 4: 'End'}

# Draw graph and labels separately
pos = nx.circular_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='yellow', node_size=700)
nx.draw_networkx_edges(G, pos, edge_color='gray')
nx.draw_networkx_labels(G, pos, labels, font_size=14, font_color='black')

plt.title("Workflow Diagram")
plt.axis('off')  # Hide axes
plt.show()

Key Parameters

Parameter Description Example Value
with_labels Show/hide node labels True
font_size Size of label text 16
font_weight Label text weight 'bold'
font_color Color of label text 'white'

Conclusion

Use with_labels=True in nx.draw() for basic node labeling. For custom labels or advanced styling, use draw_networkx_labels() with a labels dictionary.

Updated on: 2026-03-25T22:30:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements