Matplotlib fill_between() / fill_betweenx() 関数


Matplotlib 参考文档Matplotlib リファレンスドキュメント

fill_between()2本の水平な曲線の間の領域を塗りつぶすために使用され、fill_betweenx()2本の垂直な曲線の間の領域を塗りつぶします。

信頼区間、不確実性の範囲、差分領域などの可視化によく使用されます。

関数定義

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None,
    interpolate=False, step=None, **kwargs)
matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None,
    interpolate=False, step=None, **kwargs)

パラメータの説明

パラメータ型説明
x / yarray1つ目の座標軸のデータポイント
y1, y2 / x1, x2array または scalar2本の曲線。スカラーは定数線を表します。y2 のデフォルトは 0 で、x 軸まで塗りつぶします。
wherearray of boolどの区間を塗りつぶすかを指定します。True で塗りつぶし、False で塗りつぶしません。
interpolateboolTrue の場合、2本の曲線が交差する箇所でのみ補間して正確な境界を計算します。
stepstr階段状の塗りつぶし: 'pre'、'post'、'mid'
color / facecolorcolor塗りつぶしの色
alphafloat透明度
labelstr凡例ラベル
hatchstr塗りつぶしパターン: '/'、'\'、'|'、'-'、'+'、'x'、'*'

fill_between と fill_betweenx は、PolyCollection後で変更したり colorbar に渡したりできるオブジェクトを返します。


使用例

例1: x軸まで塗りつぶし(デフォルトは y2=0)

例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots(layout='constrained')

# 主曲線を描画
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
# 曲線と x 軸の間の領域を塗りつぶす
ax.fill_between(x, y, alpha=0.3, color='blue',
                label='Area under curve')

ax.set_title('fill_between: Area Between Curve and X-axis')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

例2: 信頼区間(2本の曲線の間の領域)

例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y_mean = np.sin(x) + 5                     # 平均線
y_std = 0.3 + 0.1 * x                      # 標準偏差は x の増加に伴い大きくなる

# 上限と下限
y_upper = y_mean + y_std
y_lower = y_mean - y_std

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

# 平均の両側の信頼区間を塗りつぶす
ax.fill_between(x, y_lower, y_upper,
                alpha=0.3, color='steelblue',
                label='Confidence Interval')
# 平均線を描画
ax.plot(x, y_mean, 'steelblue', linewidth=2, label='Mean')
# 上限と下限を描画
ax.plot(x, y_upper, 'steelblue', linewidth=0.5, alpha=0.5)
ax.plot(x, y_lower, 'steelblue', linewidth=0.5, alpha=0.5)

ax.set_title('Confidence Interval (fill_between)')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

例3: where パラメータによる条件付き塗りつぶし

例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)
y1 = np.sin(x)
y2 = np.cos(x)

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

ax.plot(x, y1, 'blue', label='sin(x)')
ax.plot(x, y2, 'red', label='cos(x)')

# sin(x) >= cos(x) の区間のみ塗りつぶす
ax.fill_between(x, y1, y2,
                where=(y1 >= y2),         # 条件: y1 が y2 より高い場合に塗りつぶす
                color='blue', alpha=0.3,
                label='sin ≥ cos')
# sin(x) < cos(x) の区間のみ塗りつぶし(異なる色)
ax.fill_between(x, y1, y2,
                where=(y1 < y2),
                color='red', alpha=0.3,
                label='sin < cos')

ax.set_title('Conditional Fill with where Parameter')
ax.set_xlabel('x')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

例4: fill_betweenx による垂直塗りつぶし

例

import matplotlib.pyplot as plt
import numpy as np

# fill_betweenx のパラメータの順序は (y, x1, x2) です
y = np.linspace(0, 10, 100)
x1 = 2 + np.sin(y)
x2 = 4 + np.cos(y) * 0.5

fig, ax = plt.subplots(figsize=(6, 6), layout='constrained')

ax.fill_betweenx(y, x1, x2, alpha=0.4, color='coral')
ax.plot(x1, y, 'red', linewidth=1.5, label='x1(y)')
ax.plot(x2, y, 'darkred', linewidth=1.5, label='x2(y)')

ax.set_title('fill_betweenx: Vertical Fill')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
plt.show()

よくある質問

where パラメータのデータポイントが十分滑らかではない?

True/False 境界で塗りつぶし領域が不正確な場合は、interpolate=True交差点で補間して正確な境界を計算できます。

fill_between と stackplot の違いは?

fill_between()2本の特定の曲線の間を塗りつぶし、差分や信頼区間の表示に適しています。

stackplot()複数の曲線を0から層状に積み重ね、各部分の累積総量の表示に適しています。


Matplotlib 参考文档Matplotlib リファレンスドキュメント

その他の拡張