How to change the attributes of a networkx / matplotlib graph drawing?

To change the attributes of a NetworkX/matplotlib graph drawing, you can customize various visual properties like edge colors, weights, node colors, and layouts. This allows you to create more informative and visually appealing network visualizations.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Initialize a graph with edges, name, or graph attributes.

  • Add edges with custom attributes like color and weight.

  • Extract edge attributes using NetworkX methods.

  • Position the nodes using a layout algorithm.

  • Draw the graph with customized visual attributes.

  • Display the figure using the show() method.

Example

Here's how to create a graph with colored edges and varying weights ?

import matplotlib.pyplot as plt
import networkx as nx

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

# Create a graph and add edges with attributes
G = nx.Graph()
G.add_edge(0, 1, color='r', weight=2)
G.add_edge(1, 2, color='g', weight=4)
G.add_edge(2, 3, color='b', weight=6)
G.add_edge(3, 4, color='y', weight=3)
G.add_edge(4, 0, color='m', weight=1)

# Extract edge attributes
colors = list(nx.get_edge_attributes(G, 'color').values())
weights = list(nx.get_edge_attributes(G, 'weight').values())

# Position nodes in a circular layout
pos = nx.circular_layout(G)

# Draw the graph with custom attributes
nx.draw(G, pos,
        edge_color=colors,
        width=weights,
        with_labels=True,
        node_color='lightgreen',
        node_size=800,
        font_size=16)

plt.show()

Common Customizable Attributes

Attribute Purpose Example Values
edge_color Color of edges 'red', 'blue', ['r', 'g', 'b']
width Edge thickness 1, 2, [1, 3, 5]
node_color Node fill color 'lightgreen', 'orange'
node_size Size of nodes 300, 800, [100, 200, 300]

Alternative Layout Example

You can also use different layout algorithms for node positioning ?

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_edge(0, 1, weight=2)
G.add_edge(1, 2, weight=4)
G.add_edge(2, 3, weight=6)

# Use spring layout instead of circular
pos = nx.spring_layout(G, seed=42)
weights = [G[u][v]['weight'] for u, v in G.edges()]

nx.draw(G, pos,
        width=weights,
        with_labels=True,
        node_color='skyblue',
        node_size=1000,
        edge_color='gray')

plt.title("Graph with Spring Layout")
plt.show()

Conclusion

NetworkX provides flexible options for customizing graph visualizations through edge and node attributes. Use get_edge_attributes() to extract custom properties and apply them to nx.draw() parameters for enhanced visual representation.

Updated on: 2026-03-26T19:10:43+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements