2012-11-22 66 views
15

我想繪製/草圖(matplotlib或其他python庫)一個大距離矩陣的二維網絡,其中距離將是草繪網絡的邊緣以及線和列的節點。從距離矩陣中繪製圖形或網絡?

DistMatrix = 
[  'a', 'b',  'c', 'd'], 
['a', 0,  0.3, 0.4, 0.7], 
['b', 0.3, 0,  0.9, 0.2], 
['c', 0.4, 0.9, 0,  0.1], 
['d', 0.7, 0.2, 0.1, 0] ] 

我是從搜索勾畫/情節二維網絡,例如(更大:列和行的千)距離矩陣:節點「A」連接由0.3的邊緣深度到節點「B」,節點'c'和'd'將被邊緣深度爲0.1。 我可以使用哪些工具/庫(距離矩陣可以轉換成numpy矩陣)以獲得這種網絡的草圖/圖形投影? (熊貓,matplotlib,igraph,...?)和一些導致做到這一點(我不會定義自己的Tkinter函數來做到這一點;-))? 感謝您收到的答案。

+0

在理論上,這可能是不可能的一定的距離矩陣。想象一下,例如一個包含所有條目的4×4距離矩陣1.這定義了一個三維單形。沒有辦法將這個圖嵌入到兩個維度中。該計劃在這種情況下應該做什麼? – Turion

+0

正確,所以沒有「邊緣長度」,但「邊緣深度,鏈接兩個節點 – sol

回答

21

graphviz程序neato試圖尊重邊緣長度。 doug shows a way使用networkx這樣來利用neato

import networkx as nx 
import numpy as np 
import string 

dt = [('len', float)] 
A = np.array([(0, 0.3, 0.4, 0.7), 
       (0.3, 0, 0.9, 0.2), 
       (0.4, 0.9, 0, 0.1), 
       (0.7, 0.2, 0.1, 0) 
       ])*10 
A = A.view(dt) 

G = nx.from_numpy_matrix(A) 
G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),string.ascii_uppercase)))  

G = nx.drawing.nx_agraph.to_agraph(G) 

G.node_attr.update(color="red", style="filled") 
G.edge_attr.update(color="blue", width="2.0") 

G.draw('/tmp/out.png', format='png', prog='neato') 

產生

enter image description here

+0

我試過你建議的代碼,適應我的需要(刪除A.view),它甚至沒有工作,即使只有7個節點。是正確的。什麼可能出錯?我正在使用graphviz 2.36。 – Picarus

+1

這種情況下,我錯誤''模塊'對象沒有屬性'to_agraph''。要解決我使用http://stackoverflow.com/questions/35279733/what -could-cause-networkx-pygraphviz-to-work-fine-alone-but-not-together,而是使用'nx.drawing.nx_agraph.to_agraph' – kungfujam

+0

@kungfujam:感謝您的更新。 – unutbu

14

您可以使用networkx軟件包,該軟件可以很好地解決這類問題。 調整你的矩陣,除去簡單的numpy的數組是這樣的:

DistMatrix =array([[0,  0.3, 0.4, 0.7], 
[0.3, 0,  0.9, 0.2], 
[0.4, 0.9, 0,  0.1], 
[0.7, 0.2, 0.1, 0] ]) 

然後導入networkx,並用它

import networkx as nx 
G = G=nx.from_numpy_matrix(DistMatrix) 
nx.draw(G) 

如果要繪製圖形的加權版本,你必須指定每條邊的顏色(至少,我無法找到一個更自動化的方式來做到這一點):

nx.draw(G,edge_color = [ i[2]['weight'] for i in G.edges(data=True) ], edge_cmap=cm.winter)