python networkx - 通过为图形绘制着色来标记边缘 [英] python networkx - mark edges by coloring for graph drawing

查看:267
本文介绍了python networkx - 通过为图形绘制着色来标记边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用networkx来研究图论的实现,我想知道是否有一种方法来标记给定图中的某些边?例如
- 假设我有一个图G,并且我找到了从节点x到节点y的最短路径,那么如何标记路径,以便在绘制图形时可以绘制不同的颜色?标记边可以通过设置属性颜色来实现,例如使用每个边的颜色然后在绘图时使用这些颜色的列表。在2个节点(例如 0和3 )之间对8个节点的erdos-renyi图中的蓝色的最短路径进行着色可以如下进行:

  G = nx.erdos_renyi_graph(8,0.4)
p = nx.shortest_path(G,0,3)
#设置所有边():
G [e [0]] [e [1]] ['color'] ='black'
#设置颜色的颜色属性为黑色
(len(p)-1):
G [p [i]] [p [i + 1]] ['color'] =最短路径边缘的绿色
'blue'
#存储在列表中,用于在G.edges()中为e绘制
edge_color_list = [G [e [0]] [e [1]] ['color']
nx.draw(G,edge_color = edge_color_list,with_labels = True)
plt.show()

输出图:


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?

解决方案

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

The output figure:

这篇关于python networkx - 通过为图形绘制着色来标记边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆