LoginSignup
4
6

More than 5 years have passed since last update.

matplotlibで複数のグラフをうまく描画・配置する

Last updated at Posted at 2019-02-10

matplotlibで複数のグラフをうまく描画・配置する方法を考えてみた.

使用したライブラリ

import numpy as np
import math

import matplotlib.pylab as plt

普通にグラフを描いてみる

0< x, y, z <1の乱数で構成される3次元座標(x,y,z)100サンプルを描画してみる.
データは100×3行列にまとめている.

a = np.random.rand(100, 3)
# a: 100*3行列
"""
  array([[0.6809379 , 0.61074114, 0.47836854],
        [0.04612647, 0.58351735, 0.3947241 ],
        [0.14728068, 0.39401482, 0.26023169],
        ...
        [0.48889923, 0.76056772, 0.50234148]])
"""
plot_figure.py
fig = plt.figure(figsize=(10,5))

ax1 = fig.add_subplot(1, 2, 1)
ax1.plot(a.T[0], a.T[1],"b." )
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(a.T[1], a.T[2],"b." )

出力結果:
20190210_Figure_1.png

xy平面,yz平面への正射影を可視化できた.
でも,もしデータの次元が増えてきてグラフ数が増えてくるとどうだろう.
ax1, ax2, ax3, ...とちまちま打っていくのは面倒だし,グラフの数を変えるといちいち打ち直さないといけない.また,グラフ数によってはfig.add_subplot(A, B, C)のA, B, Cの値を変更してグラフの配置を調整しないと,全体が変に横長や縦長になりそうである.

複数のグラフをいい感じに描画・配置する

前項のデータの次元を増やして隣接する2つの軸で形成される平面への正射影を可視化する.

  • 考慮したいポイント
    • ax[i](x[i]軸とx[i+1]軸でできる平面への正射影を描画する)を自動生成する
    • いい感じに配置して可視化する.全体として変に横長や縦長にならないようにする.

前項より次元を増やして,100次元座標(x[0], x[1], ..., x[100])×30サンプルからなるデータを30×100行列にまとめ,可視化してみる.全部でグラフ数は99になる.

b = np.random.rand(50, 100)
# b: 50*100行列
"""
array([[0.54480885, 0.74289626, 0.11769252, ..., 0.32641451, 0.29208658,
        0.09331203],
       [0.28205274, 0.49104085, 0.15810177, ..., 0.48538961, 0.14882423,
        0.47236724],
        ...
        [0.9908165 , 0.93689581, 0.91262158, ..., 0.92930831, 0.2450454 ,
        0.39021262]])
"""
plot_multi_figures.py
dim = b.shape[1]
graph_num = dim - 1
row_num = math.ceil(np.sqrt(graph_num))
col_num = math.ceil(np.sqrt(graph_num))

fig = plt.figure(figsize=(20, 10))
axes = [fig.add_subplot(row_num, col_num, i+1).plot(b.T[i], b.T[i+1], "b.",markersize=2) 
        for i in range(graph_num)]

出力結果:
figure3.png

99個のグラフを一挙に表示できた.全体としてもいい感じの正方形サイズ.
グラフ数が多いためひとつひとつが小さくなりすぎた気もするが…
一旦よしとしておこう.軸の設定などが必要そうなのでおいおいしていこうと思う.

4
6
2

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
4
6