Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

MatplotlibのFigureオブジェクトの書式

公開日 2023-08-10

この記事では、Figureオブジェクトの書式を設定する方法を解説します。書式の設定では、グラフの大きさや背景色などを変更可能です。

matplotlib.pyplot.subplots()関数を使うと、FigureオブジェクトはAxesオブジェクトと併せて作成されます(matplotlib.pyplot.figure()関数でもFigureオブジェクト単体を作成できます)。

matplotlib.pyplot.subplots()関数のオプションで、Figureオブジェクトの書式を設定します。主なオプションを以下に示します。

オプション説明
figsize(float, float)幅と高さ(単位:インチ。デフォルト値:(6.4, 4.8)
facecolorcolor背景色(デフォルト値:white
edgecolorcolor(デフォルト値:white
linewidthfloat枠線の太さ
frameonboolTrueの場合、枠線を描画する(デフォルト値:True

サイズ

Figureオブジェクトのサイズを変更するには、subplots()関数のfigsizeオプションで(幅, 高さ)を指定します。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(3, 4)) # 幅3インチ、高さ4インチ
ax.plot([1, 2, 3])
plt.show()

fig, ax = plt.subplots(figsize=(6, 4)) # 幅6インチ、高さ4インチ
ax.plot([1, 2, 3])
plt.show()
<Figure size 300x400 with 1 Axes>
<Figure size 600x400 with 1 Axes>

背景色・枠線

Figureオブジェクトの背景色と枠線を変更するには、subplots()関数のfacecolor, edgecolorオプションでそれぞれ指定します。

fig, ax = plt.subplots(facecolor='lightgreen')
ax.plot([1, 2, 3])
plt.show()
<Figure size 640x480 with 1 Axes>
fig, ax = plt.subplots(edgecolor='green', linewidth=5)
ax.plot([1, 2, 3])
plt.show()
<Figure size 640x480 with 1 Axes>