# From Matrix to Graph (directed and undirected) using networkx

## Issue

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.

## 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)
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: