2017-02-10 100 views
0

鑑於以下測試shapefile,其由僅折線的邊緣添加到圖表:NetworkX:從shape文件

enter image description here

我能夠再現shape文件表示的空間網絡的節點:

import networkx as nx 
import matplotlib.pyplot as plt 

G=nx.read_shp('C:\Users\MyName\MyFolder\TEST.shp') #Read shapefile as graph 
pos = {k: v for k,v in enumerate(G.nodes())} #Get the node positions based on their real coordinates 
X=nx.Graph() #Empty graph 
X.add_nodes_from(pos.keys()) #Add nodes preserving real coordinates 
nx.draw_networkx_nodes(X,pos,node_size=100,node_color='r') 
plt.xlim(450000, 470000) 
plt.ylim(430000, 450000) 

enter image description here

基本上我已使用的臨時圖G來提取最終作爲圖的一部分出現的節點的位置X。這似乎工作得很好。

我的問題:遵循相同的想法,使用G從shapefile中提取信息,我怎麼能繪製邊緣?

如果我做這樣的事情

X.add_edges_from(pos.keys()) 

然後我得到這個錯誤,在上面的行指出:

TypeError: object of type 'int' has no len() 
+0

代碼'X.add_edges_from(pos.keys())'引發了一個錯誤,因爲pos.keys()是一個整數列表。在你的情況下,每條邊都需要由2個「int」元組指定(因爲'X'中的每個節點的類型都是'int')。 更重要的是,['nx.read_shp()'](https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.readwrite.nx_shp.read_shp.html#networkx.readwrite。 nx_shp.read_shp)已經生成網絡的邊緣。我不明白你爲什麼要拋棄那些...... –

+0

我正在繪製'X',其節點是[[0,1,2,...]',所以'X'的邊緣必須是'[[ (0,1),(0,2),...]'。你對'nx.read_shp()'是正確的,但是如果你鍵入'G.edges()',你會得到一個列表,代替'(0,1)',你可以看到這兩個點的座標。所以我想我需要將'G.edges()'映射到'pos'。但我不知道該怎麼做 – FaCoffee

回答

2

添加到我的評論: nx.read_shp()持有的邊緣信息,以及。圖G具有看起來像(x,y)的節點。 draw_networkx_*pos參數需要是以節點爲關鍵字並以(x,y)作爲值的字典。

import networkx as nx 
import matplotlib.pyplot as plt 

G=nx.read_shp('C:\Users\MyName\MyFolder\TEST.shp') #Read shapefile as graph 
pos = {xy: xy for xy in G.nodes()} 
nx.draw_networkx_nodes(G,pos,node_size=100,node_color='r') 
nx.draw_networkx_edges(G,pos,edge_color='k') 
plt.xlim(450000, 470000) 
plt.ylim(430000, 450000) 
+0

我真的很喜歡這個答案,謝謝。它甚至保留了方向性,以防人們想要它。 – FaCoffee