简体   繁体   English

python.networkx - 通过着色标记边缘以绘制图形

[英]python networkx - mark edges by coloring for graph drawing

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?我正在使用 .networkx 来研究图论的实现,我想知道有没有办法在给定的图中标记一些边? 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?例如 - 假设我有一个图 G 并且我找到了从节点 x 到节点 y 的最短路径,我如何标记路径以便在我绘制图形时它会以不同的颜色绘制?

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: 在2个节点之间将蓝色的最短路径着色为例如0和3,在8个节点的erdos-renyi图中可以如下进行:

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()

The output figure: 输出数字: 在此输入图像描述

Here is another way to do it.这是另一种方法。 First create an edge_color_list of a default color (eg gray) of the same size as the number of edges.首先创建一个默认颜色(例如灰色)的 edge_color_list,其大小与边数相同。 Then iterate through the edges and replace the color in edge_color_list with red if a particular condition is met.然后遍历边缘,如果满足特定条件,则将 edge_color_list 中的颜色替换为红色。 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()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM