NetworkXで外部ファイル読み込み
2013年4月14日 コメントを残す
【実現したいこと】
どのノードとどのノードがつながっているかというリンク情報を表すedge.txtと、各ノードの座標情報を表すcoord.txtの2種類のファイルを読み込んで、グラフを描画するためのサンプルコードdraw_from_files.pyを作成する。
【グラフの種類】
重みづけなしの無向グラフ
上:【coord.txt】
下:【edge.txt】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 0 | |
5 4 | |
2 8 | |
9 1 | |
8 10 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 1 | |
0 2 | |
1 2 | |
1 3 | |
1 4 | |
3 4 |
coord.txtのn行目はノード(n-1)の座標を表している。
edge.txtの1行目はノード0とノード1にリンクが張られていることを示している。
【draw_from_files.py】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import numpy | |
import matplotlib.pyplot as plt | |
import pylab | |
import networkx as nx | |
############################################# | |
## ここからリンク関係 | |
# リンク情報のみを反映させたグラフを作成 | |
# int型を指定しないとノード名(ラベル)を単純な数値にしてくれない | |
G = nx.read_edgelist("edge.txt", nodetype=int) | |
############################################# | |
## ここから座標関係 | |
# 座標情報をndarray型として読み込む | |
pos_array=numpy.loadtxt("coord.txt", dtype='int32') | |
## arrayのままでも動くので訂正 2013.05.07 | |
# 座標情報は辞書型で表す | |
#pos = {} | |
# ndarrayの情報を「(x,y)」という値に変換する | |
#for i in range(len(pos_array)): | |
# pos[i] = (pos_array[i][0], pos_array[i][1]) | |
############################################# | |
## ここから描画関係 | |
# 描画 | |
#nx.draw(G, pos) | |
nx.draw(G, pos_array) | |
# 保存 | |
plt.savefig("test_fig.png") | |
plt.show() | |
以下は、出来上がったグラフ。