Matplotlib Figure と Axes 管理関数
Matplotlib は、Figure と Axes オブジェクトを作成・管理するための一連の関数を提供します。以下に関連するすべての関数を示します。
関数リスト
| 関数 | 機能 | pyplot | 対応するメソッド |
|---|---|---|---|
| figure() | Figure を作成またはアクティブ化 | plt.figure() | - |
| subplots() | Figure と Axes のグリッドを作成 | plt.subplots() | fig.subplots() |
| subplot() | 行と列のインデックスで単一のサブプロットを追加 | plt.subplot() | fig.add_subplot() |
| subplot2grid() | グリッドの指定位置にサブプロットを作成 | plt.subplot2grid() | - |
| subplot_mosaic() | ラベル文字列でサブプロットをレイアウト | plt.subplot_mosaic() | fig.subplot_mosaic() |
| axes() | 現在の Figure に Axes を追加 | plt.axes() | fig.add_axes() |
| gca() | 現在の Axes を取得 | plt.gca() | fig.gca() |
| gcf() | 現在の Figure を取得 | plt.gcf() | - |
| sca() | 現在の Axes を設定 | plt.sca(ax) | fig.sca(ax) |
| cla() | 現在の Axes をクリア | plt.cla() | ax.cla() |
| clf() | 現在の Figure をクリア | plt.clf() | fig.clear() |
| close() | Figure ウィンドウを閉じる | plt.close() | - |
| delaxes() | Figure から Axes を削除 | plt.delaxes(ax) | fig.delaxes(ax) |
| fignum_exists() | Figure 番号が存在するか確認 | plt.fignum_exists(n) | - |
| get_figlabels() | すべての Figure ラベルのリストを取得 | plt.get_figlabels() | - |
| get_fignums() | すべての Figure 番号のリストを取得 | plt.get_fignums() | - |
| twinx() | x 軸を共有する二重 y 軸を作成 | plt.twinx() | ax.twinx() |
| twiny() | y 軸を共有する二重 x 軸を作成 | plt.twiny() | ax.twiny() |
使用例
例1:gca/gcf/sca で現在のグラフを操作
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# 最初の Figure を作成
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# 2番目の Figure を作成
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Figure 1 が存在するか確認
print(plt.fignum_exists(1)) # True
# すべての Figure 番号を取得
print(plt.get_fignums()) # [1, 2]
# Figure 1 に切り替え
plt.figure(1)
ax = plt.gca() # 現在の Axes を取得
print(ax.get_title())
# 現在の Axes を別のものに設定
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
# 最初の Figure を作成
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# 2番目の Figure を作成
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Figure 1 が存在するか確認
print(plt.fignum_exists(1)) # True
# すべての Figure 番号を取得
print(plt.get_fignums()) # [1, 2]
# Figure 1 に切り替え
plt.figure(1)
ax = plt.gca() # 現在の Axes を取得
print(ax.get_title())
# 現在の Axes を別のものに設定
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
True [1, 2]
例2:subplot2grid で不均一なレイアウトを作成
実例
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): 3行3列のグリッド
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # 上部は行全体にまたがる
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # 左側は縦に2行またがる
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # 右上は横に2列またがる
ax4 = plt.subplot2grid((3, 3), (2, 1)) # 右中央
ax5 = plt.subplot2grid((3, 3), (2, 2)) # 右下
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): 3行3列のグリッド
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # 上部は行全体にまたがる
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # 左側は縦に2行またがる
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # 右上は横に2列またがる
ax4 = plt.subplot2grid((3, 3), (2, 1)) # 右中央
ax5 = plt.subplot2grid((3, 3), (2, 2)) # 右下
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
例3:subplot_mosaic ラベルレイアウト
実例
import matplotlib.pyplot as plt
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# ラベル名でサブプロットにアクセス
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# ラベル名でサブプロットにアクセス
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
例4:twinx/twiny 双軸
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# メインの y 軸(左側)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() は x 軸を共有する二重 y 軸を作成(右側)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# メインの y 軸(左側)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() は x 軸を共有する二重 y 軸を作成(右側)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
例5:cla/clf/close クリーンアップ操作
実例
import matplotlib.pyplot as plt
import numpy as np
# Figure を作成してプロット
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() は Axes の内容をクリア(Axes と Figure は保持)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# 再プロット
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() は Figure 全体をクリア
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() は Figure ウィンドウを閉じる
plt.close('all')
print('サンプル: cleanup complete')
import numpy as np
# Figure を作成してプロット
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() は Axes の内容をクリア(Axes と Figure は保持)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# 再プロット
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() は Figure 全体をクリア
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() は Figure ウィンドウを閉じる
plt.close('all')
print('サンプル: cleanup complete')
その他の拡張
Matplotlib リファレンスドキュメント