0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

networkxで隣接行列からグラフを作成し描画する!

Posted at

はじめに

日本語情報が見当たらなかったので,備忘録としてメモします.

環境

  • Python 3.11
  • numpy 1.24
  • networkx 3.1

方法

import numpy as np
import networkx as nx

# 隣接行列
A = np.array([
    [0, 1, 0, 1, 1],
    [1, 0, 1, 0, 1],
    [0, 1, 0, 0, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 0]
])

# グラフオブジェクトの生成
G = nx.Graph(A)

# 描画
nx.draw(G)

下図のような図が得られる.
image.png

Appendix

ちなみに,接続行列から直接グラフを生成する方法は存在しない.
そこで,次式を用いることで隣接行列を求めて,グラフを作成すればよい.

$$
\begin{align}
B^\top B &= D - A \\
B^{\prime\top} B^\prime &= D + A
\end{align}
$$
$B$は有向接続行列,$B^\prime$は無向接続行列,$D$は次数行列,$A$は隣接行列である.

以下に例を示す.

# 無向接続行列
B2 = np.array([
    [1,1,0,0,0],
    [0,1,1,0,0],
    [0,0,1,1,0],
    [1,0,0,1,0],
    [0,1,0,0,1],
    [0,0,1,0,1],
    [0,0,0,1,1],
    [1,0,0,0,1]
])

temp = B2.T@B2 # D + A 
D = np.diag(np.diag(temp))
A = temp - D # D + A - D = A

G = nx.Graph(A)
nx.draw(G)

以下の図が得られる.
image.png

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?