Python NetworkX - 标记边缘以进行图绘制的颜色着色

3

我正在使用networkx研究图论实现,我想知道是否有一种方法可以标记给定图形中的某些边?例如,假设我有一个图形G,并且我从节点x到节点y找到了最短路径,如何标记该路径,以便在绘制图形时以不同颜色绘制?


你有研究过 networkx.set_edge_attributes 吗? - Hai Vu
我看了一下,但是我还不太明白如何将它用于我的目的。 - Meni
2个回答

5

标记边可以通过设置一个属性颜色实现,例如为每个边设置您想要的颜色,然后在绘制时使用这些颜色的列表。例如,在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()

输出的图像: 在这里输入图像描述

1
这里有另一种方法来达成目标。首先创建一个默认颜色的边缘颜色列表(例如灰色),其大小与边数相同。然后遍历边缘,并在满足特定条件时将edge_color_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()

enter image description here


太棒了,非常有用,谢谢! - John Perez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接