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

Viewed 165

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?

1 Answers

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

Related