我试图在networkx中描述一个传输网络,到目前为止我一直做得很好,但问题如下: 我从txt文件中加载了edgelist,格式如下:
61 1
54 79
66 134
68 57
等等。此外,为了在正确的位置绘制网络节点,我加载了一个带有节点坐标的txt,并将其添加到图形中,其格式如下:
1 478947.434 4204495.502
2 478909.145 4204244.629
3 479065.936 4204709.003
4 478880.827 4204297.676
5 478993.409 4204167.957
之后,我运行下面的脚本,正确地描述了我的网络位置
import networkx as nx
import numpy as py
import copy
import matplotlib.pyplot as plt
import xlwings as xw
from xlwings import Book, Range
pos={}
with open(r'C:\Users\alexl\Documents\new_python\nodes_coordinates.txt') as f:
for line in f:
node, x, y = line.split()
pos[node] = float(x), float(y)
print(pos)
network0 = nx.read_edgelist(r'C:\Users\alexl\Documents\new_python\init_edgelist.txt', create_using = nx.OrderedDiGraph)
nx.draw(network0, pos = pos, with_labels = True, edge_color = G, edge_cmap = plt.cm.Reds, connectionstyle = 'arc3,rad=0.1')
plt.show()
现在,我想要的是正确地为每条边指定“权重”,并根据此属性为其着色。每个边都有3种可能的结果,0、1和2,所以我想要3种不同的颜色,例如,红色表示0,绿色表示1,蓝色表示2。我有一本Python字典,如下所示:
{0: 1.0, 1: 1.0, 2: 0.0, 3: 1.0, 4: 1.0, 5: 0.0, 6: 0.0, 7: 0.0, 8: 1.0,...
等等。第一个值(1.0)对应于上面edgelist的第一条边,第二个值(1.0)对应于第二条边,等等。但是我发现networkx不理解这一点,并且没有正确地为我的网络着色。我将dictionary转换为list并执行了以下操作:
var1 = G.values()
list1 = list(var1)
col = []
for n in range(len(list1)):
if list1[n] == 0:
col.append('b')
elif list1[n] == 1:
#col.append('r')
else:
#col.append('g')
nx.draw(network0, pos = pos, with_labels = True, edge_color = col, edge_cmap = plt.cm.Reds, connectionstyle = 'arc3,rad=0.1')
我检查了结果,但信件不正确。我认为,如果列表中有32个'0',它将使用我指定给它的颜色为32条边着色,但不是正确的边。(但每次我运行它时,相同的32条边都是这样着色的,所以它可能不是随机的。)我想知道什么是错误的。我也试着把它当作一本字典(不是转换成列表),但实际上颜色不止3种,我不知道;我不知道为什么。 我是否应该尝试将这些值(0、1、1、2等)添加到edgelist.txt中,以便正确完成赋值
传递给绘图函数的边的顺序很重要。
您需要确保
edge_color
列表(col
)的顺序与network0.edges
的顺序相同,而实际上并非如此之所以发生这种情况,是因为
network0.edges
与init_edgelist.txt
文件的顺序不同,这可能是您假设的要检查此项,请尝试打印
network0.edges
并进行比较解决方案
相反,我建议在创建
network0
时向边添加带有假装颜色的边权重,如下所示:然后,您只需提取颜色并绘制:
完整代码:
相关问题 更多 >
编程相关推荐