60
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

networkxでグラフを描く

Last updated at Posted at 2014-01-16

=
pythonのnetworkxを使ってグラフを作ってみたのでメモ

make_graph.py

# -*- encoding:utf-8 -*-

import networkx
import pylab
from matplotlib import font_manager
from itertools import combinations
from random import randint

# ノードをkey、エッジをはるノードのlistをvalueとするdict
vector = {}
persons = [u"田中", u"鈴木", u"山田", u"木村", u"吉岡"]
edge_labels = {}

for person in persons:
    # defaultdict(list)ではなく、ノードを作成するためにこうする
    vector[person] = []

for man_pair in combinations(persons, 2):
    man1, man2 = man_pair
    # 適当にエッジに値を付ける
    r = randint(1, 10)
    if r % 2:
        continue
    else:
        vector[man1].append(man2)
        edge_labels[(man1, man2)] = r

graph = networkx.Graph(vector)  # 無向グラフ
# graph = network.DiGraph(vector)  # 有向グラフ (to_undirectedで無向グラフに変換可)
pylab.figure(figsize=(3, 4))  # 横3inch 縦4inchのサイズにする
pos = networkx.spring_layout(graph)  # いい感じにplotする
# pos = networkx.random_layout(graph)  とでもすれば高速にplot出来る



# フォントを変更する(font_pathは適宜変更する)
font_path = "/usr/share/fonts/japanese/TrueType/sazanami-gothic.ttf"
font_prop = font_manager.FontProperties(fname=font_path)
networkx.set_fontproperties(font_prop)

# 見た目をいじる
networkx.draw_networkx_nodes(graph, pos, node_size=100, node_color="w")
networkx.draw_networkx_edges(graph, pos, width=1)
networkx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
networkx.draw_networkx_labels(graph, pos, font_size=16, font_color="r")

pylab.xticks([])
pylab.yticks([])

pylab.show()
pylab.savefig("graph_networkx.png")

ここで、networkxのバージョンが1.5以上でなければ日本語は表示できません。
おそらく、

ValueError: matplotlib display text must have all code points < 128 or use Unicode strings

というエラーが出るかと思います。
日本語を表示させるためにはここのパッチをnetworkx/drawing/nx_pylab.pyに適用してください

##結果
こんな感じに

graph_networkx.png

*** 参考
http://d.hatena.ne.jp/nishiohirokazu/20111121/1321849806
http://antibayesian.hateblo.jp/entry/20110828/1314491180

60
55
3

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
60
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?