【发布时间】:2016-08-02 17:38:55
【问题描述】:
我正在处理一系列可能没有完全连接的图,例如这里和那里可能存在孤立的节点集群。
根据通过每个节点的最短路径的数量,我想给每个节点一个来自cmap='jet' 的颜色。
代码块:
#Given my fragmented graph F, count the shortest paths passing through each node:
def num_spaths(F):
num_spaths = dict.fromkeys(F, 0.0)
spaths = nx.all_pairs_shortest_path(F)
for source in F:
for path in spaths[source].values():
for node in path[1:]:
num_spaths[node] += 1
return num_spaths
num_short_paths=num_spaths(F) #Calling the function on F
my_shortest_paths = num_short_paths.values() #Getting the dict values
nodes = F.nodes() #Storing the nodes in F
#Determining the number of colors
n_color = numpy.asarray([my_shortest_paths[n] for n in nodes])
如果图是连通的并且没有簇,我没有问题。如果图有簇,n_color 最终会成为一个非连续数组,因为碎片图丢失了一些节点(例如,从 0 到 N,如果图是碎片的,则并非所有节点都存在于 nodes 中)。
这会产生一个错误:IndexError: list index out of range 指向 n_color = numpy.asarray([my_shortest_paths[n] for n in nodes]) 所在的行。
为了更清楚地了解节点:
- 非分段图:
nodes=[0,1,2,3...,N] - 碎片图:
nodes=[0,2,3,...,N]
我的问题:如何构建我的n_color,考虑到我的图表中可能不存在某些节点?我认为这个问题对应于:如何构建numpy_array它是离散但不连续的,要与cmap结合使用?
编辑
我尝试使用n_color=[0,5000,10000,15000,20000,25000,30000,35000,40000,45000,50000],从而创建了一些界限,但随后出现此错误:ValueError: Color array must be two-dimensional。
【问题讨论】:
标签: python numpy matplotlib colors networkx