Matplotlib figure() 関数
figure()新しいFigure(キャンバス)を作成するか、既存のFigureをアクティブにするために使用します。
Figureはすべてのプロットのトップレベルコンテナであり、チャート全体のサイズ、DPI、およびすべてのサブプロットを管理します。
関数定義
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, *,
facecolor=None, edgecolor=None, frameon=True,
FigureClass=<class 'matplotlib.figure.Figure'>,
clear=False, layout=None, **kwargs)
引数の説明
| 引数 | 型 | 説明 |
|---|---|---|
| num | int または str | Figure識別子。整数は番号、文字列はラベル。存在しない場合は新規作成し、存在する場合は既存をアクティブにします。 |
| figsize | tuple (w, h) | Figureのサイズ(インチ)、例:(8, 6)。デフォルトはrcParamsによって決まります。 |
| dpi | float | 解像度(1インチあたりのドット数)、例:100。ピクセル出力サイズに影響します。 |
| facecolor | color | Figureの背景色 |
| edgecolor | color | Figureの枠線の色 |
| frameon | bool | Figureの背景フレームを表示するかどうか。デフォルトはTrue。 |
| clear | bool | numが既に存在する場合、先にクリアしてから使用するかどうか。 |
| layout | str または LayoutEngine | 推奨レイアウトエンジン:'constrained'、'compressed'、'tight'、'none' |
日常使用では直接呼び出すことはほとんどありません。
figure()、より一般的なのはsubplots()Figure と Axes を一度に作成することです。figure() を単独で使用するのは、主に複数のFigureを扱う場面や、キャンバス属性をカスタマイズする場合です。
使用例
例1:カスタムサイズのFigureを作成
例
import matplotlib.pyplot as plt
import numpy as np
# 指定したサイズと高DPIのFigureを作成
fig = plt.figure(figsize=(10, 4), dpi=100,
facecolor='#f8f9fa',
layout='constrained')
# サブプロットを手動で追加
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x), 'steelblue', linewidth=2)
ax1.set_title('Plot 1')
ax2.plot(x, np.cos(x), 'coral', linewidth=2)
ax2.set_title('Plot 2')
plt.show()
import numpy as np
# 指定したサイズと高DPIのFigureを作成
fig = plt.figure(figsize=(10, 4), dpi=100,
facecolor='#f8f9fa',
layout='constrained')
# サブプロットを手動で追加
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x), 'steelblue', linewidth=2)
ax1.set_title('Plot 1')
ax2.plot(x, np.cos(x), 'coral', linewidth=2)
ax2.set_title('Plot 2')
plt.show()
例2:複数のFigure管理
例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# Figure #1 を作成
fig1 = plt.figure(1, figsize=(6, 4))
ax1 = fig1.subplots()
ax1.plot(x, np.sin(x), 'blue')
ax1.set_title('Figure 1: sin(x)')
# Figure #2 を作成
fig2 = plt.figure(2, figsize=(6, 4))
ax2 = fig2.subplots()
ax2.plot(x, np.cos(x), 'red')
ax2.set_title('Figure 2: cos(x)')
# Figure #1 をアクティブにして操作を続行
plt.figure(1)
plt.plot(x, np.sin(2*x), '--', alpha=0.5)
# 特定のFigureを保存
fig1.savefig('サンプル_fig1.png', dpi=150)
fig2.savefig('サンプル_fig2.png', dpi=150)
print("サンプル: two figures saved")
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
# Figure #1 を作成
fig1 = plt.figure(1, figsize=(6, 4))
ax1 = fig1.subplots()
ax1.plot(x, np.sin(x), 'blue')
ax1.set_title('Figure 1: sin(x)')
# Figure #2 を作成
fig2 = plt.figure(2, figsize=(6, 4))
ax2 = fig2.subplots()
ax2.plot(x, np.cos(x), 'red')
ax2.set_title('Figure 2: cos(x)')
# Figure #1 をアクティブにして操作を続行
plt.figure(1)
plt.plot(x, np.sin(2*x), '--', alpha=0.5)
# 特定のFigureを保存
fig1.savefig('サンプル_fig1.png', dpi=150)
fig2.savefig('サンプル_fig2.png', dpi=150)
print("サンプル: two figures saved")
plt.show()
例3:layoutパラメータによる自動レイアウト
例
import matplotlib.pyplot as plt
import numpy as np
# layout設定の比較
# layoutを使用しない(ラベルが重なる可能性あり)
fig1 = plt.figure(1, figsize=(8, 4))
for i in range(3):
ax = fig1.add_subplot(1, 3, i+1)
ax.plot(np.random.randn(50).cumsum())
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A very long x label')
# layout='constrained' を使用(重なりを自動処理)
fig2 = plt.figure(2, figsize=(8, 4), layout='constrained')
for i in range(3):
ax = fig2.add_subplot(1, 3, i+1)
ax.plot(np.random.randn(50).cumsum())
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A very long x label')
plt.figure(1)
plt.suptitle('Without layout', y=1.02)
plt.figure(2)
plt.suptitle('With layout="constrained"', y=1.02)
plt.show()
print("サンプル: compare layout settings")
import numpy as np
# layout設定の比較
# layoutを使用しない(ラベルが重なる可能性あり)
fig1 = plt.figure(1, figsize=(8, 4))
for i in range(3):
ax = fig1.add_subplot(1, 3, i+1)
ax.plot(np.random.randn(50).cumsum())
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A very long x label')
# layout='constrained' を使用(重なりを自動処理)
fig2 = plt.figure(2, figsize=(8, 4), layout='constrained')
for i in range(3):
ax = fig2.add_subplot(1, 3, i+1)
ax.plot(np.random.randn(50).cumsum())
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A very long x label')
plt.figure(1)
plt.suptitle('Without layout', y=1.02)
plt.figure(2)
plt.suptitle('With layout="constrained"', y=1.02)
plt.show()
print("サンプル: compare layout settings")
よくある質問
figsizeのサイズ単位は何ですか?
インチ(inches)。実際のピクセルサイズ = figsize × dpi。例えばfigsize=(8,6), dpi=100800×600ピクセルの画像を生成します。
layoutはどのオプションが最適ですか?
'constrained'多くの場面で推奨されるオプションであり、サブプロットとラベルの間隔を自動的に処理します。
'compressed'さらに余白を圧縮し、データ領域を最大化したい場面に適しています。
'none'自動レイアウトを使用しない場合(デフォルト)、subplots_adjust() で手動調整できます。
その他の拡張
Matplotlib リファレンスドキュメント