FaCoffee
FaCoffee

Reputation: 7909

NetworkX: add edges to a graph from a shapefile

Given the following test shapefile, which is made of polylines only:

enter image description here

I was able to reproduce the nodes of the spatial network represented in the shapefile:

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

Basically I have used a temporary graph G to extract the positions of the nodes that eventually appeared as part of the graph X. This seems to have worked just fine.

My question: following the same idea of using G to extract information from the shapefile, how could I plot the edges?

If I do something like this

X.add_edges_from(pos.keys())

Then I get this error, pointing at the line above:

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

Upvotes: 1

Views: 1970

Answers (1)

Logan Byers
Logan Byers

Reputation: 1573

Adding on to my comment: nx.read_shp() holds the edge information as well. The graph G has nodes that look like (x,y). The pos parameter to draw_networkx_* needs to be a dictionary with a node as a key and (x,y) as the value.

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)

Upvotes: 2

Related Questions