2014-03-27 83 views
1

我創建了一個來自給定節點的最短路徑的彈簧佈局網絡。在這種情況下firm1。我想爲每個分離程度設定不同的顏色。例如,連接firm1和其他公司的所有第一個邊緣,如firm2firm3,我想要更改節點顏色firm2firm3(兩者的顏色相同)。然後從firm2firm3連接的所有公司,例如firm4firm5我想更改它們的節點顏色。但我不知道如何改變從firm1開始的每個分離度的節點顏色。這是我的代碼:Python:使用不同顏色節點的網絡彈簧佈局

import networkx as nx 
import matplotlib.pyplot as plt 
import pandas as pd 

graph = nx.Graph() 
with open('C:\\file.txt') as f: #Here, I load a text file with two columns indicating the connections between each firm 
    for line in f: 
     tic_1, tic_2 = line.split() 
     graph.add_edge(tic_1, tic_2) 

paths_from_1 = nx.shortest_path(graph, "firm1") #I get the shortest path starting from firm1 

x = pd.DataFrame(paths_from_1.values()) #I convert the dictionary of the shortest path into a dataframe 


tic_0=x[0].tolist() #there are 7 columns in my dataframe x and I convert each columns into a list. tic_0 is a list of `firm1` string 
tic_1=x[1].tolist() #tic_1 is list of all the firms directly connected to firm1 
tic_2=x[2].tolist() #tic_2 are the firms indirectly connected to firm1 via the firms in tic_1 
tic_3=x[3].tolist() #and so on... 
tic_4=x[4].tolist() 
tic_5=x[5].tolist() 
tic_6=x[6].tolist() 

l = len(tic_0) 
graph = nx.Graph() 

for i in range(len(tic_0)): 
     graph.add_edge(tic_0[i], tic_1[i]) 
     graph.add_edge(tic_1[i], tic_2[i]) 
     graph.add_edge(tic_2[i], tic_3[i]) 
     graph.add_edge(tic_3[i], tic_4[i]) 
     graph.add_edge(tic_4[i], tic_5[i]) 
     graph.add_edge(tic_5[i], tic_6[i]) 

pos = nx.spring_layout(graph_short, iterations=200, k=) 
nx.draw(graph_short, pos, font_size='6',) 
plt.savefig("network.png") 
plt.show() 

我怎樣纔能有不同的顏色節點的每個分離程度?換句話說,tic_1中的所有公司都應該有一個藍色的節點,tic_2中的所有公司都具有黃色節點顏色等。

回答

5

執行此操作的通用方法是運行最短路徑長度算法源節點分配顏色。這裏有一個例子:

import matplotlib.pyplot as plt 
import networkx as nx 

G = nx.balanced_tree(2,5) 
length = nx.shortest_path_length(G, source=0) 
nodelist,hops = zip(*length.items()) 
positions = nx.graphviz_layout(G, prog='twopi', root=0) 
nx.draw(G, positions, nodelist = nodelist, node_color=hops, cmap=plt.cm.Blues) 
plt.axis('equal') 
plt.show() 

enter image description here

你可以使用

positions = nx.spring_layout(G) 

代替。我使用graphviz圓形佈局,因爲它在繪製我使用的平衡樹方面做得更好。

+0

非常感謝。它看起來像我需要的,但我有困難,以鏈接pygraphviz和graphviz。我安裝了兩個(窗口),我不斷收到'提高ValueError(「Program%s找不到路徑。」%編) ValueError:程序twopi找不到路徑.' ...我不知道要修改哪個文件鏈接graphviz安裝文件夾的路徑。任何線索?謝謝 – Plug4

+0

我知道有些人使用PyGraphviz或Pydot與Windows一起工作。所以這是可能的 - 但我不熟悉如何正確安裝它們。 – Aric