2014年12月09日

matplotlibのfill_betweenの簡易サンプルコード

とりあえず適当に (0.0, 0.1) 〜 (1.0, 0.9) に向かう線を引いてみる。

from matplotlib import pylab as plt
import numpy as np

intercept = 0.1
coef = 0.8
line = np.linspace( intercept, intercept + 1 * coef, 2 )
plt.plot( line )
plt.ylim( (0, 1.0) )
plt.show()

plot

下に色を塗る。fill_betweenの引数は、X, Y1, Y2で、Y2は省略可。下記例ではXを0.0〜1.0、Yをlineで設定された値にする。色は黄で不透明度0.3。

plt.plot( line )
plt.fill_between( (0, 1), line, facecolor='yellow', alpha=0.3 )
plt.ylim( (0, 1.0) )
plt.show()

plot

上側に色を塗る場合は、Y2を設定。これでY1とY2の間がfillされる。Y2のデフォルトは0なので下に塗られていた。

plt.plot( line )
plt.fill_between( (0, 1), line, (1, 1), facecolor='yellow', alpha=0.3 )
plt.ylim( (0, 1.0) )
plt.show()

plot

切片より上だけ色を塗ってみる。Y2が0.1なら、0.1より上がfillされる。

plt.plot( line )
plt.fill_between( (0, 1), line, 0.1, facecolor='yellow', alpha=0.3 )
plt.ylim( (0, 1.0) )
plt.show()

plot

WHERE条件を使う準備として、複数の線を引いてみる。

intercept = 0.1
coef = 0.8
line1 = np.linspace( intercept, intercept + 1 * coef, 2 )
line2 = np.linspace( 1 - intercept, ( 1 - intercept ) + 1 * -coef, 2 )
plt.plot( line1 )
plt.plot( line2 )
plt.fill_between( (0, 1), line1, line2, facecolor='yellow', alpha=0.3 )
plt.ylim( (0, 1.0) )
plt.show()

plot

WHEREを使ってみる。line1がline2以上になってるところだけfillする。

plt.plot( line1 )
plt.plot( line2 )
plt.fill_between( (0, 1), line1, line2, where=line1>line2, facecolor='yellow', alpha=0.3, interpolate=True )
plt.ylim( (0, 1.0) )
plt.show()

plot

line3を作って色を被せてみる。

line3 = np.linspace( 0.5, 0.5, 2 )
plt.plot( line1 )
plt.plot( line2 )
plt.plot( line3 )
plt.fill_between( (0, 1), line1, line2, facecolor='blue', alpha=0.7, interpolate=True )
plt.fill_between( (0, 1), line1, line3, where=line3>line2, facecolor='yellow', alpha=0.7, interpolate=True )
plt.fill_between( (0, 1), line1, line3, where=line3<line2, facecolor='red', alpha=0.7, interpolate=True )
plt.ylim( (0, 1.0) )
plt.show()

plot