Search code examples
pythonnetworkxsubgraph

partition graph into sungraphs based on node's attribute NetworkX


I'm using Networkx to compute some measures of a graph such as diameter, clustering coefficient, etc. It's straight forward how to do this for graph as a whole. What I'm interested in is finding these measures between nodes that have same attribute(say color). I'm thinking if I could partition the graph into different sub graphs, where nodes in each sub graph are of the same color, then I could accomplish go ahead and measure diameter in this sub graph. So my question is: Is there a way to partition a graph into sub graphs which contain nodes of same color?

I would really appreciate any insight.


Solution

  • Use Graph.subgraph(nodes)

    NetworkX 2.x+:

    Demo

    import networkx as nx
    
    G = nx.Graph()
    
    G.add_nodes_from([1, 2, 3], color="red")
    G.add_nodes_from([4, 5, 6])
    G.nodes  # NodeView((1, 2, 3, 4, 5, 6))
    
    # create generator
    nodes = (
        node
        for node, data
        in G.nodes(data=True)
        if data.get("color") == "red"
    )
    subgraph = G.subgraph(nodes)
    subgraph.nodes  # NodeView((1, 2, 3))
    

    older NetworkX's

    Iterate over (Graph.iter_nodes()) and filter the nodes based on your criteria. Pass that list to Graph.subgraph() and it'll return a copy of those nodes and their internal edges.

    For example:

    G = nx.Graph()
    # ... build or do whatever to the graph
    nodes = (n for n, d in G.nodes_iter(data=True)) if d.get('color') == 'red')
    subgraph = G.subgraph(nodes)