Skip to main content

Shapefile to graph/network converter in Python

Project description

# python-s2g

(S)hapefile (2) Graph/network converter in Python

[![Build Status](](

When we process GIS data, a non-trivial problem is the conversion from shape lines to graph or network data structure.
The latter may benefit from these out-of-box graphical libraries such as [networkx](
and [igraph]( But the conversion is a headache to components open communities.
This mostly urges me to finish this tiny but useful library.

# Install

pip install -U s2g

# Usage

You have two alternative ways to construct the graph. One is reading from a raw shapefiles with `LineString` objects.
(Under the hood, I involve [fiona]( to read geometries and
[shapely]( to analyze the data.).
Currently, this tool only supports conversion to *undirected graph*.

from s2g import ShapeGraph
import networkx as nx

sg = ShapeGraph(shapefile='path/to/roads.shp', to_graph=True)
assert isinstance(sg.graph, nx.Graph)

The other way is designed for programmable usage or time-consuming process where intermediate data could be sniffed or
saved. Here is an example to read lines with [fiona]:

from s2g import ShapeGraph
import fiona
from shapely.geometry import shape, LineString

shp = 'path/to/shapefile.shp'

with as source:
geoms = []
for r in source:
s = shape(r['geometry'])
if isinstance(s, LineString):

# create ShapeGraph object from a list of lines
sg = ShapeGraph(geoms, to_graph=False)

# detect major components
mc = sg.gen_major_components()
# major components are mc[2]

# convert the largest component to networkx Graph
graph = sg.to_networkx() # equivalently sg.graph

Dive into [source doc]( to discover other functionalities.

## References

* [shp2graph]( in R by Binbin Lu, as well as [his talk]( on useR! 2011
* [A Tutorial on Topology Correction of Shapefiles Using GRASS](

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

s2g- (48.4 kB view hashes)

Uploaded source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page