I am trying to use networkx.read_shp to create a MultiGraph from a shape file. I understand that the function needs to be modified since it usually creates a DiGraph I attempt by trying this:

def read_multi_shp(path, simplify=True, geom_attrs=True, strict=True):
        from osgeo import ogr
    except ImportError:
        raise ImportError("read_shp requires OGR: http://www.gdal.org/")

    if not isinstance(path, str):

    net = nx.MultiGraph() #My first change
    shp = ogr.Open(path)
    if shp is None:
        raise RuntimeError("Unable to open {}".format(path))
    for lyr in shp:
        fields = [x.GetName() for x in lyr.schema]
        for f in lyr:
            g = f.geometry()
            if g is None:
                if strict:
                    raise nx.NetworkXError("Bad data: feature missing geometry")
            flddata = [f.GetField(f.GetFieldIndex(x)) for x in fields]
            attributes = dict(zip(fields, flddata))
            attributes["ShpName"] = lyr.GetName()
            # Note:  Using layer level geometry type
            if g.GetGeometryType() == ogr.wkbPoint:
                net.add_node((g.GetPoint_2D(0)), **attributes)
            elif g.GetGeometryType() in (ogr.wkbLineString,
                for edge in edges_from_line(g, attributes, simplify,
                    e1, e2, attr = edge
                    net.add_edge(e1, e2)
                    net[e1][e2][0].update(attr) #Second change and perhaps the one that is not working
                if strict:
                    raise nx.NetworkXError("GeometryType {} not supported".

    return net

The rest of the function stays the same. When checking eges I can see that when there are parallel edges one of them seems to have an empty dictionary instead of the attributes (despite these being present in the shapefile). I have seen a similar question before but it seems to be using an outdated version of networkx. Is there any way to make a multigraph that has parallel edges with their attributes?

  • A solution to your problem is provided in stackoverflow NetworkX - How to create MultiDiGraph from Shapefile? – gene Jun 25 at 12:22
  • Yes, I had seen that, I can do something similar and it will work but it will be multiple directed graph and I was trying to get an undirected one. I suppose converting it after is an option. – Mrplayr Jun 25 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.