Matplotlibのワイヤーフレーム#
※記事内に商品プロモーションを含むことがあります。
公開日
この記事では、Matplotlibでワイヤーフレームのグラフを出力する方法を解説します。ワイヤーフレームでは、点と点を結ぶ線で3次元の形状を表現します。
ワイヤーフレームの基本#
plt.subplots()
のsubplot_kw
オプションに{'projection': '3d'}
という辞書形式データを与えることで、3次元のプロットになります。ワイヤーフレームとするには、さらにax.plot_wireframe()
メソッドを使います。
ax.plot_wireframe()
メソッドにはx, y, z座標を与えます。以下に例を示します。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.arange(0, 4*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.sin(Y)
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()

なお、変数X
, Y
, Z
はいずれも同じ大きさの2次元配列となります。
print(X.shape)
print(Y.shape)
print(Z.shape)
(126, 63)
(126, 63)
(126, 63)
ax.plot_wireframe()
メソッドの主なオプションを以下に示します。
引数 |
型 |
説明 |
---|---|---|
rcount, ccount |
int |
行・列方向の最大サンプル数。データ点数がこれより多い場合、ダウンサンプリングされる(デフォルト値:50) |
rstride, cstride |
int |
ダウンサンプリングするときに飛ばすデータ点数 |
color |
str |
線の色 |
linewidth |
float |
線の太さ |
alpha |
float |
線の透明度 |
rcount
とrstride
は片方のみ指定できます。同様に、ccount
とcstride
も片方のみ指定できます。
データのダウンサンプリング#
rcount
, rstride
, ccount
, cstride
で描画する頂点の数を変更できます。
rcount=15
, ccount=15
として、描画点数をx, y軸方向にそれぞれ15点とした例を以下に示します。デフォルト値の50とした場合よりもメッシュが荒くなっていることが分かります。
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, rcount=15, ccount=15)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()

線の色#
color
オプションで線の色を指定できます。
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, color="green")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()

指定可能な色については以下のページを参照下さい。
線の太さ#
linewidths
オプションで線の太さを指定できます。
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, linewidths=0.6)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()

線の透明度#
線の透明度を指定するには、alpha
オプションを使用します。0から1の範囲の値を取り、値が小さいほど透明になります(デフォルトは1)。以下にalpha=0.3
とした例を示します。
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, alpha=0.3)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
