我正在處理一系列可能未完全連接的圖形,例如,在這裏和那裏可能存在孤立的節點簇。Python:在着色圖時出錯numpy.asarray
根據通過每個節點的最短路徑的數量,我想給每個節點的顏色來自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
。