# How to Convert a Numpy Matrix to a NetworkX Graph in Python

To convert a Numpy Matrix to a NetworkX Graph in Python, use the networkx library, which provides from_numpy_array() and draw() function.

## Step 1: Install NetworkX

If you haven’t already installed NetworkX, you can do so using pip:

``pip install networkx``

## Step 2: Load the libraries

Import NumPy and NetworkX in your Python script:

``````import numpy as np

import networkx as nx
``````

## Step 3: Creating a numpy matrix

In an adjacency matrix, the element at (i, j) is non-zero if there is an edge from node i to node j.

``````matrix = np.array([[0, 1, 1],
[1, 0, 0],
[1, 0, 0]])
``````

## Step 4: Convert to a NetworkX Graph

### For an Undirected Graph

``G = nx.from_numpy_array(matrix)``

#### Visualize the graph

``````import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# Example: 3x3 matrix
matrix = np.array([[0, 1, 1],
[1, 0, 0],
[1, 0, 0]])

G = nx.from_numpy_array(matrix)

nx.draw(G, with_labels=True)
plt.show()
``````

Output

### For Directed Graph

``````import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# Example: 3x3 matrix
matrix = np.array([[0, 1, 1],
[1, 0, 0],
[1, 0, 0]])

G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)

nx.draw(G, with_labels=True)
plt.show()``````

Output

The nodes in the NetworkX graph are numbered, corresponding to the indices in the matrix.

If your adjacency matrix is weighted (i.e., the matrix entries represent edge weights), the weights are preserved in the graph.

This site uses Akismet to reduce spam. Learn how your comment data is processed.