DSS
DSS

Reputation: 35

How to color the edges of the graph that make the minimal spanning tree

I have a complete graph G with 4 nodes. I need to colour the edges that make a minimal spanning tree. How can I do that with networkx and python?

Upvotes: 1

Views: 304

Answers (1)

CDJB
CDJB

Reputation: 14546

networkx.draw takes an optional edge_color keyword argument which allows you to specify the color of individual edges. Using the minimum_spanning_tree function, we can color an edge red if it is within the minimum spanning tree, and black otherwise.

Code

import networkx as nx
G = nx.complete_graph(4)

mst = nx.minimum_spanning_tree(G)

edge_colors = ['red' if e in mst.edges else 'black' for e in G.edges]

nx.draw(G, edge_color=edge_colors)

Output

enter image description here

Upvotes: 1

Related Questions