LoginSignup
1
1

More than 5 years have passed since last update.

NetworkX と Matplotlib の使い方

Last updated at Posted at 2019-04-18

次のページの最初のサンプルです。日本語を使えるようにしました。
Python networkx.draw_networkx_nodes() Examples

example_01.py
#! /usr/bin/python
#
#   example_01.py
#
#                       Apr/18/2019
# ------------------------------------------------------------------
import sys
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
# ------------------------------------------------------------------
def draw_graph(edges):
    G = nx.DiGraph()
    G.add_edges_from(edges)

    values = [1.0 for node in G.nodes()]

    # Specify the edges you want here
    edge_colours = ['black' for edge in G.edges()]
    black_edges = [edge for edge in G.edges()]

    # Need to create a layout when doing
    # separate calls to draw nodes and edges
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('Reds'), node_color = values, node_size=4800)
    nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True)
#    nx.draw_networkx_labels(G,pos,font_size=12,font_family='sans-serif')
    nx.draw_networkx_labels(G,pos,font_size=12,font_family='TakaoExMincho')

    plt.axis('off')
    plt.show()
#
# ------------------------------------------------------------------
edges = [('明治','大正'),('大正','昭和'),('昭和','平成'), \
        ('平成','令和'),('令和','明治')]
draw_graph(edges)
# ------------------------------------------------------------------

実行結果
matplot01.png

日本語を使えるようにするには、次のようにします。

font_family='TakaoExMincho'

次のバージョンで確認しました。

$ python
Python 3.7.3 (default, Mar 26 2019, 21:43:19) 
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import networkx
>>> import matplotlib
>>> networkx.__version__
'2.2'
>>> matplotlib.__version__
'3.0.3'
1
1
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
1
1