How can one modify the outline color of a node in networkx using Matplotlib?

When working with NetworkX graphs in matplotlib, you can modify the outline color of nodes using the set_edgecolor() method on the node collection returned by draw_networkx_nodes().

Basic Example

Here's how to create a graph and set red outline color for all nodes ?

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

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

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

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

# Get node positions using spring layout
pos = nx.spring_layout(G)

# Draw nodes and get the node collection
nodes = nx.draw_networkx_nodes(G, pos)

# Set outline color to red
nodes.set_edgecolor('red')

# Draw edges and labels
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)

plt.show()

Different Outline Colors for Different Nodes

You can also specify different outline colors for individual nodes ?

import networkx as nx
import matplotlib.pyplot as plt

# Create a simple graph
G = nx.Graph()
G.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'D'), ('A', 'D')])

pos = nx.spring_layout(G)

# Draw nodes with different outline colors
nodes = nx.draw_networkx_nodes(G, pos, node_color='lightblue')

# Set different outline colors for each node
outline_colors = ['red', 'green', 'blue', 'orange']
nodes.set_edgecolor(outline_colors)

# Set outline width
nodes.set_linewidth(3)

nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)

plt.show()

Key Parameters

Parameter Description Example Values
set_edgecolor() Sets outline color 'red', 'blue', ['red', 'green']
set_linewidth() Sets outline thickness 1, 2, 3 (pixels)
node_color Sets fill color in draw_networkx_nodes() 'lightblue', 'yellow'

Complete Customization Example

Here's a more comprehensive example with custom styling ?

import networkx as nx
import matplotlib.pyplot as plt

# Create a graph
G = nx.cycle_graph(5)
pos = nx.circular_layout(G)

# Draw nodes with custom styling
nodes = nx.draw_networkx_nodes(G, pos, 
                              node_color='lightgreen',
                              node_size=800)

# Set thick red outline
nodes.set_edgecolor('darkred')
nodes.set_linewidth(4)

# Draw edges and labels
nx.draw_networkx_edges(G, pos, alpha=0.5)
nx.draw_networkx_labels(G, pos, font_size=16, font_weight='bold')

plt.title("NetworkX Graph with Custom Node Outlines")
plt.axis('off')
plt.show()

Conclusion

Use set_edgecolor() on the node collection returned by draw_networkx_nodes() to modify outline colors. You can set uniform colors or different colors for each node, and combine with set_linewidth() for thickness control.

Updated on: 2026-03-25T20:08:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements