Help us understand the problem. What is going on with this article?

networkxでグラフを描く

More than 5 years have passed since last update.

=
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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away