Search code examples
pythonnumpynetworkx

How can I solve this error?: networkx.exception.NetworkXError: ('Adjacency matrix is not square.', 'nx,ny=(10, 11)')


I am trying to create a graph from a numpy array using networkx but I get this error: networkx.exception.NetworkXError: ('Adjacency matrix is not square.', 'nx,ny=(10, 11)') Someone know how to solve it?

My_Diz = {'X120213_1_0013_2_000004': array([[  0.        ,  23.40378234,  30.29631001,  49.45217086,
         53.47727757,  74.32949293,  73.27188558,  93.85556785,
        132.31971186, 118.04532327,  88.1557181 ],
       [  0.        ,   0.        ,  34.41617904,  39.54024761,
         34.25713329,  51.79037103,  51.33810652,  70.9900316 ,
        109.76561471,  98.51724406,  69.76728919],
       [  0.        ,   0.        ,   0.        ,  26.66788605,
         42.7133817 ,  79.11779461,  65.88325262,  89.68664703,
        125.91837789, 102.22926865,  71.58316322],
       [  0.        ,   0.        ,   0.        ,   0.        ,
         22.98401022,  65.5730092 ,  44.53195174,  68.64071584,
        102.34029705,  75.76571351,  45.22368742],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,  43.0377496 ,  23.19245567,  47.19664886,
         83.42653241,  65.0762151 ,  35.66216118],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,  30.28626571,  29.1448064 ,
         64.72235299,  72.76481721,  56.93798086],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,  24.18622881,
         60.591058  ,  49.69530936,  27.61846738],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
         39.02763348,  46.26701103,  40.06206332],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,  44.72240673,  62.0541588 ],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,  30.69921172]])}

for k,v in My_Diz.items():
    G = nx.from_numpy_matrix(v)
    nx.draw(G)

Solution

  • Your Matrix is not square. You have to give networkx a square matrix. Since the matrix is (n × n+1), and it is triangular, you can do that :

    for k,v in My_Diz.items():
      r, c = v.shape
      M = np.zeros((c,c))
      M[:r, :c] = v
      M[:c, :r] += v.T
      G = nx.from_numpy_matrix(M)
      nx.draw(G)