我正在使用networkx研究图论实现,我想知道是否有一种方法可以标记给定图形中的某些边?例如,假设我有一个图形G,并且我从节点x到节点y找到了最短路径,如何标记该路径,以便在绘制图形时以不同颜色绘制?
标记边可以通过设置一个属性颜色实现,例如为每个边设置您想要的颜色,然后在绘制时使用这些颜色的列表。例如,在8个节点的erdos-renyi图中将节点0和3之间的最短路径着色为蓝色,可以按照以下步骤完成:
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()
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