1
import numpy as np
import networkx as nx
import pylab as plt

A=np.array([[0,0,1,0],[1,0,0,0],[1,0,0,1],[1,0,0,0],[1,1,0,0]])
G = nx.DiGraph(A)

when iam trying to print graph of above matrix it shows error

pos=[[0,0],[0,1],[1,0],[1,1],[2,1]]
nx.draw(G,pos)
plt.savefig("2trial.png",format="PNG")
4
  • You have an empty element in your array ,, Commented Sep 5, 2019 at 14:08
  • after correcting it also it shows error Commented Sep 5, 2019 at 14:16
  • I think you need to understand how to correctly construct a Graph in NetworkX, I see no support to pass an array of lists containing 4 elements, normally one passes an array of pairs or 2-element sequences. It's unclear what you're trying to achieve here Commented Sep 5, 2019 at 14:20
  • actually iam trying to print the graph of matrix(which is not a square matrix) Commented Sep 5, 2019 at 14:38

1 Answer 1

1

Networkx has a special function to construct a graph from numpy adjacency matrix:

G = nx.from_numpy_matrix(A)

However, an adjacency matrix must be square:

In graph theory and computer science, an adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph.

So you can't create a graph with your matrix because it is not an adjacency matrix. You should convert it to a 5x5 matrix and then send to nx.from_numpy_matrix function:

import numpy as np
import networkx as nx

A=np.array([[0,0,1,0,0],[1,0,0,0,1],[1,0,0,1,0],[1,0,0,0,0],[1,1,0,0,1]])
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
pos=[[0,0],[0,1],[1,0],[1,1],[2,1]]
nx.draw(G,pos)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.