Matplotlib contour() / contourf() 関数
contour()等高線(輪郭線)を描画し、contourf()塗りつぶし等高線を描画します。
両方とも2次元スカラー場(地形図、温度場、圧力場など)の可視化に使用されます。
関数定義
pyplot インターフェース
matplotlib.pyplot.contour(*args, **kwargs) matplotlib.pyplot.contourf(*args, **kwargs)
Axes インターフェース
Axes.contour(X, Y, Z, levels=None, **kwargs) Axes.contourf(X, Y, Z, levels=None, **kwargs)
パラメータの説明
| パラメータ | 型 | 説明 |
|---|---|---|
| X, Y | 2D array-like または 1D array | グリッド点の x 座標と y 座標。1D 配列を渡すと、meshgrid によって自動的に拡張されます。 |
| Z | 2D array-like | 各グリッド点の関数値(高さ)。形状は X, Y と同じです。 |
| levels | int または array-like | 等高線のレベル:整数の場合は N 本を自動生成し、配列の場合は具体的なレベル値を示します。 |
| colors | color または list | 等高線の色(contour 用) |
| cmap | str または Colormap | カラーマップ(contourf 用)。例:'viridis'、'terrain' |
| alpha | float | 透明度 0-1 |
| linewidths | float または list | 線幅(contour 用) |
| linestyles | str または list | 線種(contour 用)。例:'solid'、'dashed' |
| extend | str | levels の範囲外の色の処理:'neither'/'both'/'min'/'max' |
| antialiased | bool | アンチエイリアスの有無(contourf)。デフォルトは True |
clabel() の補足説明
clabel()等高線上に数値ラベルを追加するために使用します。
Axes.clabel(CS, levels=None, **kwargs)
使用例
例 1:基本の等高線 + 塗りつぶし等高線の比較
実例
import matplotlib.pyplot as plt
import numpy as np
# 2次元グリッドと関数値を作成
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y) # 2次元関数
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# 左の図:輪郭線(contour)
cs1 = ax1.contour(X, Y, Z, levels=10, cmap='viridis')
ax1.clabel(cs1, inline=True, fontsize=8) # ラベルを追加
ax1.set_title('contour() - Line Contours')
# 右の図:塗りつぶし等高線(contourf)
cs2 = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
fig.colorbar(cs2, ax=ax2, label='Value')
# 境界線を重ねる
ax2.contour(X, Y, Z, levels=15, colors='black', linewidths=0.3)
ax2.set_title('contourf() - Filled Contours')
for ax in [ax1, ax2]:
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
import numpy as np
# 2次元グリッドと関数値を作成
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y) # 2次元関数
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# 左の図:輪郭線(contour)
cs1 = ax1.contour(X, Y, Z, levels=10, cmap='viridis')
ax1.clabel(cs1, inline=True, fontsize=8) # ラベルを追加
ax1.set_title('contour() - Line Contours')
# 右の図:塗りつぶし等高線(contourf)
cs2 = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
fig.colorbar(cs2, ax=ax2, label='Value')
# 境界線を重ねる
ax2.contour(X, Y, Z, levels=15, colors='black', linewidths=0.3)
ax2.set_title('contourf() - Filled Contours')
for ax in [ax1, ax2]:
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
例 2:カスタム levels
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 150)
y = np.linspace(-5, 5, 150)
X, Y = np.meshgrid(x, y)
# ガウス分布の丘
Z = np.exp(-((X-1)**2 + Y**2) / 4) +
np.exp(-((X+1)**2 + Y**2) / 3)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
# カスタム levels:0.1 から 1.0 まで、間隔 0.1
custom_levels = np.arange(0.1, 1.1, 0.1)
cs = ax.contourf(X, Y, Z, levels=custom_levels,
cmap='YlOrRd', extend='both')
cbar = fig.colorbar(cs, ax=ax, label='Height')
ax.contour(X, Y, Z, levels=custom_levels,
colors='black', linewidths=0.5)
ax.set_title('Custom Levels Contour')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
import numpy as np
x = np.linspace(-5, 5, 150)
y = np.linspace(-5, 5, 150)
X, Y = np.meshgrid(x, y)
# ガウス分布の丘
Z = np.exp(-((X-1)**2 + Y**2) / 4) +
np.exp(-((X+1)**2 + Y**2) / 3)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
# カスタム levels:0.1 から 1.0 まで、間隔 0.1
custom_levels = np.arange(0.1, 1.1, 0.1)
cs = ax.contourf(X, Y, Z, levels=custom_levels,
cmap='YlOrRd', extend='both')
cbar = fig.colorbar(cs, ax=ax, label='Height')
ax.contour(X, Y, Z, levels=custom_levels,
colors='black', linewidths=0.5)
ax.set_title('Custom Levels Contour')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
例 3:地形図スタイル(terrain colormap)
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4, 4, 200)
y = np.linspace(-4, 4, 200)
X, Y = np.meshgrid(x, y)
# 地形をシミュレーション:2つの山頂 + 1つの谷
Z = 3 * np.exp(-((X+2)**2 + Y**2) / 3) +
2 * np.exp(-((X-1)**2 + (Y-1)**2) / 2) -
1 * np.exp(-((X+0.5)**2 + (Y-2)**2) / 1.5)
fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')
# terrain colormap で地形図をシミュレーション
cs = ax.contourf(X, Y, Z, levels=20, cmap='terrain', extend='both')
fig.colorbar(cs, ax=ax, label='Elevation', shrink=0.8)
ax.contour(X, Y, Z, levels=20, colors='black', linewidths=0.3,
alpha=0.4)
ax.set_title('Terrain-style Contour Map')
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.show()
print("サンプル: terrain contour displayed")
import numpy as np
x = np.linspace(-4, 4, 200)
y = np.linspace(-4, 4, 200)
X, Y = np.meshgrid(x, y)
# 地形をシミュレーション:2つの山頂 + 1つの谷
Z = 3 * np.exp(-((X+2)**2 + Y**2) / 3) +
2 * np.exp(-((X-1)**2 + (Y-1)**2) / 2) -
1 * np.exp(-((X+0.5)**2 + (Y-2)**2) / 1.5)
fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')
# terrain colormap で地形図をシミュレーション
cs = ax.contourf(X, Y, Z, levels=20, cmap='terrain', extend='both')
fig.colorbar(cs, ax=ax, label='Elevation', shrink=0.8)
ax.contour(X, Y, Z, levels=20, colors='black', linewidths=0.3,
alpha=0.4)
ax.set_title('Terrain-style Contour Map')
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.show()
print("サンプル: terrain contour displayed")
よくある質問
contour と contourf はいつどちらを使う?
contour():明確な境界線を見るのに適しています。例:気圧の等値線。
contourf():連続的に変化する場を示すのに適しています。例:温度分布。
一般的な方法は両者を重ねることです:contourf で色を塗りつぶし、contour で境界線を重ねます。
X,Y は 2D である必要がありますか?
いいえ。X と Y として 1D 配列を渡すと、matplotlib は自動的にnp.meshgrid(X, Y)meshgrid を呼び出して2次元グリッドを生成します。Z は meshgrid 後の形状と一致する必要があります。
その他の拡張