pythongraphnetworkxgraphvizdistance-matrix

Vizualize distance matrix into graph


For the following distance matrix:

∞, 1, 2
∞, ∞, 1
∞, ∞, ∞

I would need to visualise the following graph:
That's how it should look like

I tried with the following code:

import networkx as nx
import numpy as np
import string

dt = [('len', float)]
A = np.array([ (0, 1, None, 3, None),
               (2, 0, 4, 1, None),
               (5, None, 0, 3, None),
               (None, None, None, 0, None),
               (None, None, None, 2, 0),
               ])*10
A = A.view(dt)

G = nx.from_numpy_matrix(A)   

G = nx.drawing.nx_agraph.to_agraph(G)

G.node_attr.update(color="red", style="filled")
G.edge_attr.update(color="blue", width="2.0")

G.draw('out.png', format='png', prog='neato')

but I cannot seem to input infinity (∞) to show that there is no connection. I tried with None, -1, and even but nothing seems to work right, so if anyone has any idea how I can visualise that distance matrix, please let me know.


Solution

  • It's not immediately obvious if this is what you are after, but one option is to use np.inf to denote the infinity. Below is a snippet where edges with value np.inf are removed, but whether this makes sense will depend on the context:

    import networkx as nx
    import numpy as np
    
    A = np.array(
        [
            (0, 1, np.inf),
            (2, 0, 4),
            (5, np.inf, 0),
        ],
        dtype="float",
    )
    
    # if edge is np.inf replace with zero
    A[A == np.inf] = 0
    
    G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
    G = nx.drawing.nx_agraph.to_agraph(G)
    G.node_attr.update(color="red", style="filled")
    G.edge_attr.update(color="blue", width="0.3")
    G.draw("out.png", format="png", prog="neato")