Search code examples
pythonnumpynetworkx

From Matrix to Graph (directed and undirected) using networkx


Starting from the following bumpy matrix I would like to create a graph using the python library Networkx

matrix([[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 1],
        [0, 0, 0, 1, 0, 0, 2, 0],
        [2, 2, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 1, 0, 0, 0]])

Where:

  • 0 means that the node is NOT connected to another node
  • 1 means that the node is connected to another node
  • 2 means that the node has an outgoing arrow to another node (e.g., 1 --> 6)

The problem is that I'm able to draw directed or undirected graph, but not a mix of both.

Thanks for your help


Solution

  • #libraries
    import networkx as nx
    import numpy as np
    
    #input
    X = np.array([[0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0],
            [2, 0, 0, 0, 0, 0, 0, 1],
            [0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0, 0, 2, 1],
            [0, 0, 0, 1, 0, 0, 2, 0],
            [2, 2, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 0, 1, 0, 0, 0]])
    
    
    G = nx.DiGraph(X>0)
    nx.draw_kamada_kawai(G, with_labels=True)
    

    graph

    In this way you have that undirected edges are bidirectional connection. I think there is not another way to implement your graph in networkx because the mixed graph are not allowed, as mentioned here:

    -Is it possible to add undirected and directed edges to a graph object in networkx

    -MixedGraph and MixedMultiGraph

    The only other solution I can imagine is to build a directed graph and separately an undirected graph, but it obliviously depends on what is your goal and on what the graph is to be used for.