LoginSignup
35
28

More than 5 years have passed since last update.

matplotlibのsubplotで共通の設定をオサレにやる

Last updated at Posted at 2017-08-18

やりたいこと

matplotlibのsubplotで描画した全ての軸に対して、グリッドやラベルなど共通の設定をしたい。
Example1.png

やり方 1

  1. 軸の一覧を取得する。
  2. 軸毎にループ
  3. 現在の軸を変更
# 1. 軸の一覧取得
axs = plt.gcf().get_axes()

# 2. 軸毎にループ
for ax in axs:
    # 3. 現在の軸を変更
    plt.axes(ax)

コード例

import matplotlib.pyplot as plt
import numpy as np

# データ
x  = np.linspace(-np.pi, np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# figure
plt.figure(figsize=(8,4))

# プロット1
plt.subplot(1,2,1)
plt.plot(x,y1,label='sin')

# プロット2
plt.subplot(1,2,2)
plt.plot(x,y2,label='cos')

# 軸の一覧取得
axs = plt.gcf().get_axes()

# 軸毎にループ
for ax in axs:
    # 現在の軸を変更
    plt.axes(ax)

    # 凡例を表示
    plt.legend(loc=2)

    # グリッド
    plt.grid(linestyle='--')

    # 軸ラベル
    plt.xlabel('x')
    plt.ylabel('y')

    # 軸の範囲
    plt.xlim([-np.pi, np.pi])
    plt.ylim([  -1.2,   1.2])

# 図の調整
plt.tight_layout()

やり方 2

  1. データとラベル等をリストにする。
  2. enumerateを使ってループ
  3. plt.subplotは+1するのを忘れない
# 1. データとラベル等をリストにする。
Y    = [y1, y2]
lbls = ['sin', 'cos']

# 2. enumerateを使ってループ
for i, y in enumerate(Y):

    # 3. plt.subplotは+1するのを忘れない
    plt.subplot(1,2,i+1)

コード例 2

# figure
plt.figure(figsize=(8,4))
# list
Y    = [y1, y2]
lbls = ['sin', 'cos']

for i, y in enumerate(Y):
    # サブプロット
    plt.subplot(1,2,i+1)

    # プロット
    plt.plot(x,y,label=lbls[i])

    # 凡例を表示
    plt.legend(loc=2)

    # グリッド
    plt.grid(linestyle='--')

    # 軸ラベル
    plt.xlabel('x')
    plt.ylabel('y')

    # 軸の範囲
    plt.xlim([-np.pi, np.pi])
    plt.ylim([  -1.2,   1.2])

# 図の調整
plt.tight_layout()

以下補足情報

gca, gcf

plt.gcf()で現在のfigureを、plt.gca()で現在のaxesを取得できる。またplt.axes()で現在の軸を指定できる。

階層構造

 matplotlibのfigureは、MATLABと同じく以下の図のように階層構造になっている。
図1.png

figureの中にaxesがあり、axesの中にlinesがある。plt.gcf().get_axes()で現在のfigureにある全ての軸をリストで取得できる。他にはplt.gca().get_lines()だと現在のaxesにある全てのlinesを取得できる。

35
28
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
35
28