I'm using networkx to study graph theory implementations and I wondered is there a way to mark some of the edges in a given graph? for example - say I have a graph G and I found a shortest path from a node x to node y, how can I mark the path so that when I draw the graph it will be drawn in different color?
2 Answers
5
votes
Marking edges can be accomplished by setting an attribute color for instance with the color you want for each edge then using a list of these colors while drawing. Coloring the shortest path in blue between 2 nodes for instance 0 and 3 in an erdos-renyi graph of 8 nodes can be done as follows:
G = nx.erdos_renyi_graph(8,0.4)
p = nx.shortest_path(G,0,3)
# Set all edge color attribute to black
for e in G.edges():
G[e[0]][e[1]]['color'] = 'black'
# Set color of edges of the shortest path to green
for i in xrange(len(p)-1):
G[p[i]][p[i+1]]['color'] = 'blue'
# Store in a list to use for drawing
edge_color_list = [ G[e[0]][e[1]]['color'] for e in G.edges() ]
nx.draw(G,edge_color = edge_color_list, with_labels = True)
plt.show()
0
votes
Here is another way to do it. First create an edge_color_list of a default color (e.g. gray) of the same size as the number of edges. Then iterate through the edges and replace the color in edge_color_list with red if a particular condition is met. In this case, the condition is if the edge belongs to the shortest path edge list:
import networkx as nx
from matplotlib import pyplot as plt
G = nx.Graph()
G.add_edges_from([(1, 'b'), (1, 'c'), (1, 'd'), (3, 'a'), (2, 'c'), (2, 'e'), (3, 'b'),
(3, 'c'), (3, 'd'), (4, 'a'), (4, 'e'), (5, 'a'), (3, 'e')])
sp = nx.shortest_path(G,"d", "e")
#create a list of shortest-path edges:
sp_edges = [(sp[i],sp[i+1]) for i in range(len(sp)-1)]
edge_color_list = ["grey"]*len(G.edges)
#replace the color in edge_color_list with red if the edge belongs to the shortest path:
for i, edge in enumerate(G.edges()):
if edge in sp_edges or (edge[1],edge[0]) in sp_edges:
edge_color_list[i] = 'red'
nx.draw(G, with_labels=True, edge_color = edge_color_list)
plt.show()
networkx. set_edge_attributes
? – Hai Vu